Two-Sided Order Book Matching with Unit Orders
Heaps, Sorting & SearchModel answerLast updated
Simulate a simple exchange: buys and sells of size one arrive in sequence, cross against the best resting price, and you return the total value of all executed trades.
Order Book Simulator
You are building the core of a toy exchange. Every order is for exactly one unit and is described by a pair [side, price]:
side = 1is a buy (bid).side = -1is a sell (ask).priceis a positive integer.
Orders arrive one at a time, in array order. Unfilled orders sit in an order book until a later order trades against them (these are called resting orders). Handle each arriving order as follows:
- Arriving buy at price
p. While the book holds a resting sell priced<= p, trade against the resting sell with the lowest price. Both orders leave the book. - Arriving sell at price
p. While the book holds a resting buy priced>= p, trade against the resting buy with the highest price. Both orders leave the book. - If the arriving order cannot trade (or has already traded), it is not added to the book. If it finds no counterparty, it is added to the book and rests there.
Assume each trade executes at the resting order's price, that is, the price of the order that was already in the book.
Return the sum of the prices of all trades after every order has been processed.
Example
orders = [[1,5], [1,7], [-1,6], [-1,4], [1,8], [-1,9]]
The sell at 6 trades with the resting buy at 7, and the sell at 4 trades with the resting buy at 5. The buy at 8 and the sell at 9 do not cross, so both rest. The answer is 7 + 5 = 12.
What to deliver
- A function
match_orders(orders) -> int. - The data structures you chose and why they support fast matching.
- The time and space complexity.
- How you resolve ties deterministically when several resting orders share the same best price.
- Edge cases you would test.
Hints
Hint 1
Each side of the book only ever needs its best price: the lowest ask and the highest bid. Which structure gives you the minimum quickly, and how could you reuse it for a maximum?
Hint 2
If the best opposing price does not cross the arriving order, no other resting order on that side can cross it either. Think about why the book never contains a buy and sell that could trade with each other.
Hint 3
Store an arrival counter next to each price in the heap entries. Equal prices then fall back to earliest arrival first, which makes counterparty selection deterministic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach in one paragraph
Keep two priority queues: a min-heap of resting sells and a max-heap of resting buys. For each arriving order, look only at the top of the opposite heap. If it crosses, pop it and add its price to the total. Otherwise push the arriving order onto its own side's heap. Each order costs O(log n), so the whole run is O(n log n).
Clarify the contract first
Three points are worth confirming before coding.
- Trade price. The statement fixes it as the resting order's price. This matches the usual rule that the quote already in the book sets the price. If the aggressor's price were wanted instead, only the line that adds to the total changes.
- Repeat clause. Every order has size one, so an arriving order can match at most once. The "repeat while matches exist" wording would matter only with larger quantities, and the loop structure below extends to that case.
- Ties. If several resting orders share the best price, the earliest arrival trades first (FIFO). With unit sizes the total is unchanged, but the choice of counterparty becomes deterministic, which matters if you later report fills per order.
Data structures
- Asks (resting sells): a min-heap of
(price, seq). The top is the cheapest sell, with the earliest arrival winning among equals. - Bids (resting buys): Python's
heapqis a min-heap, so store(-price, seq). The top is then the highest buy, again with the earliest arrival winning among equals.
seq is the index of the order in the input. Because it is unique, tuple comparison never has to look past two integers.
Why checking only the top is enough
The book is never crossed after any step: every resting buy is priced strictly below every resting sell. If a buy at b and a sell at s with b >= s were both resting, whichever arrived later would have traded on arrival, since the heap top is the best available counterparty. It would never have been inserted.
Given this invariant, if the cheapest resting sell is too expensive for an arriving buy, all other sells are too. The same reasoning applies to an arriving sell against the highest bid. So one comparison with the heap top decides whether a trade happens.
Each trade removes the resting order by popping it, and the arriving order is never pushed, so no order can trade twice.
Code
import heapq
def match_orders(orders: list[list[int]]) -> int:
bids: list[tuple[int, int]] = [] # (-price, seq): max-heap by price
asks: list[tuple[int, int]] = [] # (price, seq): min-heap by price
total = 0
for seq, (side, price) in enumerate(orders):
if side == 1: # arriving buy
if asks and asks[0][0] <= price:
ask_price, _ = heapq.heappop(asks)
total += ask_price # resting order's price
else:
heapq.heappush(bids, (-price, seq))
elif side == -1: # arriving sell
if bids and -bids[0][0] >= price:
neg_bid, _ = heapq.heappop(bids)
total += -neg_bid # resting order's price
else:
heapq.heappush(asks, (price, seq))
else:
raise ValueError(f"bad side {side} at index {seq}")
return total
Because orders are unit-sized, the if is equivalent to the while in the rules: after one trade the arriving order is gone.
Walkthrough
For [[1,5],[1,7],[-1,6],[-1,4],[1,8],[-1,9]]:
| Order | Book effect | Running total |
|---|---|---|
| Buy 5 | no asks, rests | 0 |
| Buy 7 | no asks, rests | 0 |
| Sell 6 | best bid 7 >= 6, trade at 7 | 7 |
| Sell 4 | best bid 5 >= 4, trade at 5 | 12 |
| Buy 8 | no asks, rests | 12 |
| Sell 9 | best bid 8 < 9, rests | 12 |
Result: 12.
Complexity
- Time: O(n log n). Each order does at most one push or one pop on a heap of size at most n.
- Space: O(n), in the worst case when nothing ever trades (for example, all buys).
Trade-offs and alternatives
- A balanced BST or sorted container keyed by price gives the same O(log n) bounds. It is preferable if the problem adds cancellations, because a binary heap cannot remove an arbitrary element efficiently. You can use lazy deletion (mark cancelled and skip when it reaches the top), but that lets the heap grow.
- Production engines typically use a map from price level to a FIFO queue, plus a hash map from order id to its queue node, so cancels are O(1) and best-price lookup is cheap.
- Larger quantities: replace the
ifwith a loopwhile remaining > 0 and top crosses. Each iteration fillsmin(remaining, resting_qty)and addsprice * filledto the total. A partially filled resting order stays on top with reduced quantity, which preserves its time priority. Leftover quantity then rests. Cost becomes O((n + t) log n), where t is the number of fills.
Edge cases to test
- Empty input returns 0.
- Equal prices trade, since the comparison is inclusive (buy 10 against sell 10).
- One-sided flow (all buys or all sells) returns 0.
- Opposite-direction crossing:
[[1,10],[-1,8]]trades at 10, the resting buy's price, not 8. - Many resting orders at one price: the earliest arrival is consumed first.
- Alternating orders that fully cancel out leave an empty book.
- An unknown side value should raise an error rather than be silently ignored.
Common mistakes
- Using the arriving order's price as the trade price without noting the assumption.
- Forgetting to negate prices for the bid heap, which makes the buy side pick the lowest bid.
- Comparing against the wrong end of the book, such as matching an arriving buy to the highest ask.
- Using
<or>instead of<=and>=, which drops trades at equal prices. - Pushing the arriving order into the book even after it has traded.
- Scanning or sorting the whole book on each order, which degrades to O(n^2) or worse.