progress

~/problems / Order books / Order books and matching engines

Crypto order matching

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Coinbase

A small exchange opens with two books of one-coin limit orders: sells[j] is the lowest price seller j accepts, buys[i] the highest price buyer i pays.

The engine walks the buys in order. Buy i takes the cheapest open sell priced <= buys[i] and fills at that sell's price, using the sell up. If there's none, buy i goes unfilled (it never waits for later).

Write match_orders(buys: list[int], sells: list[int]) -> tuple[list[int], list[int]] returning fills (the price each buy paid, or -1) and left (unfilled sell prices, ascending).

match_orders(buys=[100, 90, 120, 95], sells=[105, 92, 98, 130])
# fills: [92, -1, 98, -1]
#   buy 100 -> cheapest sell is 92, fills at 92
#   buy 90  -> cheapest open sell is 98 > 90, unfilled
#   buy 120 -> fills at 98
#   buy 95  -> cheapest open sell is 105 > 95, unfilled
# left:  [105, 130]

Up to 200,000 orders per side; prices in 1..10**9, may repeat; either list may be empty.

⭐ Bonus: scanning the open sells for every buy still passes; a speed test with 200,000-order books earns a star at O(log n) per buy.

Show hint

only the cheapest open sell ever matters. Which structure hands you the minimum and removes it in O(log n)?

Topic: Order books and matching engines. Price levels, price-time priority, partial fills, cancels.

0:00
Ctrl ' run · Ctrl ↵ submit
esc