The Number of Orders in the Backlog problem simulates a stock exchange order book. You receive a sequence of orders: each is either a buy order (at most some price) or a sell order (at least some price). Matching orders execute immediately; unmatched orders go into a backlog. Return the total number of unmatched orders after all orders are processed. This coding problem uses two heaps for buy and sell backlogs.
Citadel, Coinbase, Jane Street, and Robinhood ask this because stock exchange simulation is directly relevant to their business. It tests heap-based order matching simulation — a practical algorithm used in financial trading systems. The array, heap, and simulation interview pattern is directly exercised.
Max-heap for buy orders + min-heap for sell orders. For a new buy order at price p: match against the cheapest sell order in the sell backlog (min-heap top) while sell_top ≤ p and there are sell orders. Process quantity. Remaining unmatched quantity goes into the buy backlog (max-heap). Vice versa for sell orders. Return sum of all remaining quantities in both backlogs, mod 10^9+7.
Orders: [(10,5,"buy"),(15,2,"sell"),(25,1,"buy"),(30,4,"sell"),(5,6,"sell")].
Order book simulation is a classic heap problem where buy orders use a max-heap (match highest buy first) and sell orders use a min-heap (match cheapest sell first). Practice this pattern in the context of "priority matching" simulations — it appears in scheduling, resource allocation, and financial system design questions. Understanding why the heap type differs for buy vs sell is the key conceptual insight.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Operations to Exceed Threshold Value II | Medium | Solve | |
| Final Array State After K Multiplication Operations II | Hard | Solve | |
| Take Gifts From the Richest Pile | Easy | Solve | |
| Time to Cross a Bridge | Hard | Solve | |
| Total Cost to Hire K Workers | Medium | Solve |