1153. Called to the Front

Medium3.5 points estimatedSimulationHash TableQueue

People numbered 1..n stand in a line, in increasing order from the front. A host reads out the array calls, and each time a person is called they walk to the very front of the line while everyone who was ahead of them steps back by one place. Nobody else changes their relative order.

Return the final line, from front to back, as an array of person numbers. A person called several times is placed by their latest call only, and people who were never called keep their original relative order behind all the called ones. Constraints: 1 <= n <= 2*10^5, 1 <= calls.length <= 2*10^5 and 1 <= calls[i] <= n. Moving people one at a time is too slow; aim for O(n + calls.length) time and O(n) space.

Example 1

Input:
n = 5, calls = [2,4,2]
Output:
[2,4,1,3,5]
Explanation:

Person 2 is called twice but only the latest call counts; the newest call (person 2) leads, then person 4, then the uncalled 1, 3, 5 in order.

Example 2

Input:
n = 3, calls = [3]
Output:
[3,1,2]
Explanation:

Person 3 jumps to the front and the rest keep their order, giving [3, 1, 2].

Example 3

Input:
n = 4, calls = [1,2,3,4]
Output:
[4,3,2,1]
Explanation:

Each call pushes the previous caller back, so the last caller stands first: [4, 3, 2, 1].

Constraints

1 ≤ n ≤ 2*105
1 ≤ calls.length ≤ 2*105
1 ≤ calls[i] ≤ n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n + q)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…