Problem solving - Coding Interview Question?

Viewed 179

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).

2 Answers

Here's a solution in Matlab.

Hints:

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);

Typing this from a phone so not sure if the syntax is correct.

Using list comprehension we can flatten a list of lists, and using [x]*y we can create a list that repeats x y times.

q1 = [e for l in [[i+1]*px for i,px in enumerate(p)] for e in l]

Im sure q2 is similar?

Related