Ride-hailing app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-503monotonic-stack · stacks
A ride-hailing app splits the day into time slots and records the demand in each slot: the number of ride requests. The same schedule repeats every day, so after the last slot of the day comes the first slot of the next.
For each slot, the dispatcher wants the demand of the next slot, in schedule order, whose demand is strictly higher. The search may wrap round past the end to the start. If no slot is higher, the answer is -1. A schedule can have up to 100,000 slots.
Write next_busier_slot(demand).
demand is a list of whole numbers, one for each slot, in schedule order. The schedule is circular: the slot after the last one is slot 0.i, look at the slots after it, going forward and wrapping round, for at most one full turn (slot i itself is not looked at). Find the first one with a strictly higher demand and report its demand.-1.Input: demand = [40, 90, 30, 70, 20]
Output: [90, -1, 70, 90, 40]Walk the cycle twice. The first lap pushes each slot on a stack of slots waiting for a higher demand. The second lap only answers: it pops, but pushes nothing.
| Step | Slot (demand) | Slots popped (answer) | Waiting stack after (slots) |
|---|---|---|---|
| 0 | 0 (40) | none | 0 |
| 1 | 1 (90) | slot 0: 90 | 1 |
| 2 | 2 (30) | none | 1, 2 |
| 3 | 3 (70) | slot 2: 70 | 1, 3 |
| 4 | 4 (20) | none | 1, 3, 4 |
| 5 | 0 (40), second lap | slot 4: 40 | 1, 3 |
| 6 | 1 (90), second lap | slot 3: 90 | 1 |
| 7 to 9 | 2, 3, 4, second lap | none | 1 |
Slot 1 (demand 90) is the only slot left on the stack, so its answer stays -1. The output is [90, -1, 70, 90, 40].
Input: demand = [5, 5, 5]
Output: [-1, -1, -1]Every slot has the same demand. A higher slot never exists, so every answer is -1.
Input: demand = [3, 1, 2]
Output: [-1, 2, 3]Slot 0 has 3, the highest, so it finds nothing. Slot 1 (1) finds 2. Slot 2 (2) is the last slot: it wraps round to slot 0 and finds 3.
1 ≤ number of slots ≤ 10^51 ≤ each demand ≤ 10^9A plan that walks round the cycle from every slot costs up to n steps for each of n slots: 10^10 when the demand is flat. That is too slow.
So the work must be close to n steps in all. Each slot should be handled a constant number of times, even though its answer may sit on the other side of the wrap.