Skip to content
LeetQuant
QD01 Data Structures and Algorithms

QD01 · Data Structures and Algorithms · Lesson 1 of 7

Heaps, Hash Maps & Order Books

Priority queues, top-k and streaming medians, and how to design a limit order book with the right complexities.

25 min

The structures that matter

StructureInsertRemove / popLookupTypical use
Hash mapO(1)O(1) avgO(1)O(1) avgO(1)O(1) avgorder id → order
Binary heapO(log⁡n)O(\log n)pop min O(log⁡n)O(\log n)min O(1)O(1)top-kk, schedulers
Balanced tree / sorted mapO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n), ordered iterationprice levels
Deque / linked listO(1)O(1) at endsO(1)O(1) at ends (or given a node)O(n)O(n)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 kk largest trades from a stream, hold a min-heap of size kk. Each new item is compared with the smallest kept item, the heap's root, and replaces it if larger. Cost: O(nlog⁡k)O(n \log k) time and O(k)O(k) memory, much better than sorting when k≪nk \ll n.

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 O(1)O(1) without scanning.

Operations: add O(log⁡L)O(\log L) for a new level or O(1)O(1) for an existing one (LL = number of levels); cancel O(1)O(1); 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 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 100×10.01+50×10.01+30×10.02=1,802.10100 \times 10.01 + 50 \times 10.01 + 30 \times 10.02 = 1{,}802.10, 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).