Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem solving - Coding Interview Question?

So I came along this mock interview question, I have to find a solution to this problem without using functions repelem or repmat. Only 3 lines of code are allowed with the format: (only one = operator per line)
p=... , q1=.... , q2=....,

So far I only got a solution using repelem, but when I try to change my code I always have to use more lines of code when indexing. Very thankful for any hints you got for me :)

p=[4 2 5 3 1]

q1 = repelem((1:length(p)),p)
q2 = repelem(p,p)

Here is the question, if anyone wants to try by himself (designed for MATLAB, but can be done anywhere)

Let p be a vector with k different positive integer elements and s=sum(p). Two vectors q1 and q2 shall be determined such that:

• q1 is a vector of length s. The first p(1) elements of q1 are equal to 1, the next p(2) elements are equal to 2, . . . , the last p(k) elements are equal to k.

• q2 is a vector of length s. The first p(1) elements of q2 are equal to p(1), the next p(2) elements are equal to p(2), . . . , the last p(k) elements are equal to p(k).

like image 855
Sheograph Avatar asked Mar 11 '26 09:03

Sheograph


1 Answers

Here's a solution in Matlab.

Hints:

  • Use implicit expansion (or bsxfun) and nonzeros to build q1.
  • q2 is easily obtained from p and q1.

Code (give it a try yourself first!):

p = [4 2 5 3 1]; % example input
q1 = nonzeros(((1:max(p)).'<=p).*(1:numel(p))).';
q2 = p(q1);

like image 65
Luis Mendo Avatar answered Mar 13 '26 01:03

Luis Mendo