Chat app~25 min2s · 256 MBtarget O(m log m) time, O(m) spaceheaps
You work on the support desk of a chat app. Each support ticket has an urgency number, and the longer a ticket waits, the more urgent it becomes: its urgency grows by rate every second. An agent always takes the ticket with the highest urgency at that moment.
A customer can also write again, which resets the ticket: it gets a new urgency, and the growth starts again from that second. Your team lead asks: "In which order are the tickets served?" A day holds up to 200,000 actions, and thousands of tickets can wait together.
Write serve_order(rate, ops).
ops[i] = [kind, time, id, value] is one action. The times never fall from one action to the next. There are three kinds:
1: ticket id arrives at second time with the urgency value. Every id arrives at most once.2: ticket id is reset at second time to the urgency value. If that ticket is not waiting, nothing happens.3: an agent takes a ticket at second time. id and value are 0 and are ignored.now is value + rate × (now - time), where value and time come from its arrival or its latest reset.Input: rate = 2, ops = [[1, 0, 7, 10], [1, 1, 3, 12], [1, 2, 9, 5], [3, 4, 0, 0], [2, 5, 9, 30], [3, 6, 0, 0], [3, 7, 0, 0], [3, 8, 0, 0]]
Output: [3, 9, 7, -1]| Second | Action | Urgency of each waiting ticket now | Result |
|---|---|---|---|
| 4 | take | ticket 7: 18, ticket 3: 18, ticket 9: 9 | 3: the urgency ties at 18, and 3 is the smaller id |
| 5 | reset 9 to 30 | ||
| 6 | take | ticket 7: 22, ticket 9: 32 | 9 |
| 7 | take | ticket 7: 24 | 7 |
| 8 | take | none | -1 |
Input: rate = 5, ops = [[3, 0, 0, 0], [1, 1, 4, 20], [2, 2, 8, 99], [3, 3, 0, 0]]
Output: [-1, 4]The first take finds nothing waiting. The reset names ticket 8, which never arrived, so nothing happens.
Input: rate = 0, ops = [[1, 0, 2, 5], [1, 0, 1, 5], [3, 9, 0, 0], [3, 9, 0, 0]]
Output: [1, 2]With a rate of 0 the urgency never grows. Tickets 1 and 2 tie at 5, and the smaller id goes first.
0 ≤ rate ≤ 1,0001 ≤ ops.length ≤ 200,000, and every row has 4 numberskind is 1, 2 or 3. Times, ids and values are from 0 to 1,000,000,000, and the times never fall.Working out the urgency of every waiting ticket at each take costs one step for each waiting ticket. With 100,000 tickets waiting and 100,000 takes, that is about 5,000,000,000 steps.
A heap finds the best ticket in about 17 steps. But urgency changes every second, so you need a key that does not change while a ticket waits.
A key can reach rate × time = 1,000 × 1,000,000,000 = 10^12, so it needs 64 bits.