Music streaming app~15 min2s · 256 MBtarget O(n log n) time, O(n) spacequeues
You work on a live quiz show in a streaming app. Contestants wait in one queue. The front contestant answers questions for one visit, which lasts at most per_visit questions. A contestant with questions left walks to the back of the queue, and anyone else leaves.
Your team lead asks: "In which order do the contestants leave?" A show can have 100,000 contestants, each with up to 1,000,000 questions.
Write finish_order(turns, per_visit).
turns[i] is the number of questions contestant i + 1 must answer. Contestants are numbered from 1, and they start in the queue in that order.per_visit questions, or all the questions they have left if that is fewer.Input: turns = [3, 1, 2, 5], per_visit = 2
Output: [2, 3, 1, 4]Follow the queue. A visit answers up to 2 questions.
| Visit | Contestant | Questions left | Answered | Result |
|---|---|---|---|---|
| 1 | 1 | 3 | 2 | back of the queue with 1 |
| 2 | 2 | 1 | 1 | leaves |
| 3 | 3 | 2 | 2 | leaves |
| 4 | 4 | 5 | 2 | back of the queue with 3 |
| 5 | 1 | 1 | 1 | leaves |
| 6 | 4 | 3 | 2 | back of the queue with 1 |
| 7 | 4 | 1 | 1 | leaves |
Input: turns = [4, 4, 4], per_visit = 4
Output: [1, 2, 3]Every contestant finishes in one visit, so they leave in queue order.
Input: turns = [1], per_visit = 5
Output: [1]One contestant has one question, so one visit finishes it.
1 ≤ len(turns) ≤ 100,000 and 1 ≤ turns[i] ≤ 1,000,0001 ≤ per_visit ≤ 1,000,000The show can need up to 100,000 × 1,000,000 = 100,000,000,000 questions when per_visit is 1. A queue simulation that handles one question at a time cannot finish in 2 seconds. You need to know the order without replaying the show.