Bank app~25 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
A savings app has a small market where members trade units of a fund. Members post bids, the prices at which they would buy, and asks, the prices at which they would sell. A board shows the best bid, the highest price anyone offers to pay, and the best ask, the lowest price anyone asks.
Orders can be cancelled at any time. The board only shows orders: a separate system does the matching.
Write run_book(commands, args).
commands[i] is "bid", "ask", "cancel" or "best"."bid" and "ask" have args[i] = [id, price]: post an order with this id. Every id is used once."cancel" has args[i] = [id]: remove the order with that id. An id that is unknown or already cancelled changes nothing."best" has args[i] = [0]: report the highest price among live bids and the lowest price among live asks. Use -1 for a side with no live order."best" command (best bid, then best ask), in order.Input: commands = ["bid", "bid", "ask", "best", "cancel", "best", "ask", "best"], args = [[1, 100], [2, 105], [3, 110], [0], [2], [0], [4, 108], [0]]
Output: [105, 110, 100, 110, 100, 108]Each best command reports the best bid and the best ask.
| Step | Command | Live bids | Live asks | Output |
|---|---|---|---|---|
| 1 | bid 1 at 100 | 100 | ||
| 2 | bid 2 at 105 | 100, 105 | ||
| 3 | ask 3 at 110 | 100, 105 | 110 | |
| 4 | best | 100, 105 | 110 | 105, 110 |
| 5 | cancel 2 | 100 | 110 | |
| 6 | best | 100 | 110 | 100, 110 |
| 7 | ask 4 at 108 | 100 | 108, 110 | |
| 8 | best | 100 | 108, 110 | 100, 108 |
The table shows the live prices after each command. Cancelling order 2 removes the best bid, so the next best bid is 100.
Input: commands = ["best"], args = [[0]]
Output: [-1, -1]An empty board reports -1 on both sides.
Input: commands = ["ask", "cancel", "cancel", "best"], args = [[1, 50], [1], [1], [0]]
Output: [-1, -1]The second cancel finds nothing to remove. The board is empty, so best reports -1 and -1.
1 ≤ commands.length ≤ 100,000, and args has the same length1 ≤ id ≤ 100,000 and 1 ≤ price ≤ 1,000,000,000"bid" and "ask" uses a new idScanning every live order for each best command costs about n × n / 4 steps, 2.5 × 10^9 at n = 100,000. A heap gives the best price on each side in O(1) and a post in O(log n). A heap cannot remove an order from its middle, so cancelled orders are marked and thrown away when they reach the top.