Facebook | Onsite | Sort array

Anonymous User
4785
Apr 26, 2021
Apr 26, 2021

Got asked this question for Facebook onsite (London) round today. Have never seen this before. Let me know if there is already a question on LC for this.

Description : You are given an array and a integer k.
Let's define the target position of every element as the index at which it would appear if this element was sorted.
For example, if the array is [1, 2, 3, 4, 5] then the target position for 1 is 0, for 2 is 1 and so on.

Now, every element in the array is present at either its target position or k indexes away from its target position.

For instance, if the target position of an element is index 5, and k = 2, then this element may be present anywhere between indexes [3, 7] included.

The task is to sort the array.

Example input : [1, 4, 5, 2, 3, 8, 7, 6], k = 2
Expected output : [1, 2, 3, 4, 5, 6, 7, 8]

I could only come up with a TC : O(n logk), SC : O(k) solution involving a heap and sliding window of size k.

Is there a O(n) solution?
My interviewer was a brick wall throughout the interview, I have no clue what they wanted.

Comments (9)