The structures that matter
| Structure | Insert | Remove / pop | Lookup | Typical use |
|---|---|---|---|---|
| Hash map | avg | avg | avg | order id → order |
| Binary heap | pop min | min | top-, schedulers | |
| Balanced tree / sorted map | , ordered iteration | price levels | ||
| Deque / linked list | at ends | at ends (or given a node) | FIFO queues at a price |
Python's heapq is a min-heap over a list; push negated values for a max-heap.
Top-k and streaming statistics
To keep the largest trades from a stream, hold a min-heap of size . Each new item is compared with the smallest kept item, the heap's root, and replaces it if larger. Cost: time and memory, much better than sorting when .
import heapq
def top_k(sizes: list[float], k: int) -> list[float]:
heap: list[float] = []
for s in sizes:
if len(heap) < k:
heapq.heappush(heap, s)
elif s > heap[0]:
heapq.heapreplace(heap, s)
return sorted(heap, reverse=True)
A streaming median uses two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalanced so their sizes differ by at most one. The median is read from the tops.
Designing a limit order book
An order book holds resting buy orders (bids) and sell orders (asks). Orders at the same price fill in arrival order (price–time priority). A sound design:
- Price levels: a sorted map from price to level for each side, so the best bid and ask are the ends of the map. If prices sit on a bounded tick grid, an array indexed by tick with a pointer to the best level is faster still.
- Each level: a FIFO queue (often an intrusive doubly linked list) of orders, plus the total quantity.
- Order index: a hash map from order id to its node, so cancels and modifications are without scanning.
Operations: add for a new level or for an existing one ( = number of levels); cancel ; match an incoming order by walking from the best level, filling the oldest orders first.
Worked example
matching an aggressive order
The ask side holds 100 @ 10.01 (order A, earliest), 50 @ 10.01 (order B), and 200 @ 10.02. A buy order for 180 with limit 10.02 arrives. What fills?
Show solutionHide solution
Walk the asks from the best price. At 10.01, A fills 100 then B fills 50 (time priority), leaving 30 to fill. At 10.02, 30 of the 200 fill. The buyer pays , and 170 remain at 10.02.
Knowledge check
What is the time complexity of finding the k largest of n numbers with a size-k min-heap?
Knowledge check
In a two-heap streaming median, which half is kept in a max-heap?
Knowledge check
Which structure makes cancelling an order by id O(1) in an order book?
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).