Ride-hailing app~22 min2s · 256 MBtarget O(m log m) time, O(m) spaceheaps
You work on a ride-hailing app. Riders send ride requests, and each request has an id and an urgency score. A dispatcher serves the waiting request with the highest urgency. A rider can also cancel a request before it is served.
Your team lead asks: "In which order are the requests served, given the log of the day?" The log holds up to 200,000 actions, and many requests can be waiting at the same time.
Write serve_order(ops).
ops[i] = [kind, id, urgency] is one action, in time order. There are three kinds:
1: a request with this id and urgency arrives. Every id arrives at most once.2: the request with this id is cancelled. urgency is 0 and is ignored. If that request is not waiting, because it never arrived, was served, or was cancelled already, nothing happens.3: the dispatcher serves one request. id and urgency are 0 and are ignored.Input: ops = [[1, 5, 30], [1, 2, 50], [1, 9, 50], [3, 0, 0], [2, 9, 0], [3, 0, 0], [3, 0, 0]]
Output: [2, 5, -1]| Action | Waiting afterwards | Result |
|---|---|---|
| add 5 (urgency 30) | 5 | |
| add 2 (urgency 50) | 5, 2 | |
| add 9 (urgency 50) | 5, 2, 9 | |
| serve | 5, 9 | 2: the highest urgency 50, and 2 is smaller than 9 |
| cancel 9 | 5 | |
| serve | none | 5 |
| serve | none | -1 |
Input: ops = [[2, 4, 0], [1, 4, 10], [3, 0, 0], [2, 4, 0], [3, 0, 0]]
Output: [4, -1]The first cancel names a request that has not arrived, and the second names one already served. Neither does anything.
Input: ops = [[3, 0, 0]]
Output: [-1]1 ≤ len(ops) ≤ 200,000kind is 1, 2 or 3. Ids and urgencies are from 0 to 1,000,000.Scanning all waiting requests for the best one at every serve costs up to 100,000 steps when many wait. With 100,000 serves that is about 10 billion steps. A heap finds the best request in about 17 steps. A cancel needs the request's position in the heap, and the heap cannot find an id by itself.