Process queue with wait limits
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests simulation, queue and counting sort.
A single server works through a line of n processes in first-in, first-out order. Process i (0-indexed, in line order) can wait at most wait[i] seconds. Once that much time has passed, it gives up and leaves the line, even if it was never served.
The clock starts at t = 0 with all n processes in line. At every second t = 1, 2, 3, ... two things happen at the same moment:
- The process at the front of the line is served and leaves.
- Every process still in line with
wait[i] <= tleaves because its limit has run out.
Implement:
def queue_sizes(wait: list[int]) -> list[int]:
...
Return the number of processes in line at t = 0, then after each second, up to and including the first second at which the line is empty.
Constraints
0 <= n <= 10^51 <= wait[i] <= 10^9- Aim for better than
O(n^2).
Example 1
wait = [3, 1, 2, 10]
output = [4, 2, 1, 0]
At t=1 the process with wait 3 is served and the one with wait 1 expires, leaving [2, 10]. At t=2 the 2 is served. At t=3 the 10 is served.
Example 2
wait = [5, 1, 1, 2]
output = [4, 1, 0]
At t=1 the 5 is served and both 1s expire. At t=2 the 2 is served, and the line is empty.
Clarifying questions
- If the front process's limit runs out at the same second it would be served, is it served or does it leave?
- Is the output the size after both events of each second?
- Is the output
[0]for an empty line? - Can
waitvalues be larger thann, making them never expire?
What a strong answer covers
- Sees that the line empties within
nseconds, so the output has at mostn + 1entries and the expired processes need not be removed one by one. - Keeps a pointer to the next unserved process in line order; at each second, skips processes that already expired, serves the first live one, and marks it served.
- Computes the size after second
tas the number of processes withwait > tminus those of them already served, using a count of waits per value (capped atn + 1) or a sorted array. -
O(n log n)with sorting, orO(n)with counting, againstO(n^2)from rescanning the line each second. - Tests both examples, all waits equal to
1, and all waits large (one served per second).
Follow-ups
- Return the order in which processes are served.
- Processes arrive over time instead of all at
t = 0. - The server takes several seconds per process.
Where it's asked
What it tests
simulation · queue · counting sort
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
