Trees and heaps: BSTs, priority queues and range queries
CS · Chapter 312 min readAsked at Hudson River Trading, Jump, Citadel Securities, Optiver
Assumes Linear structures: arrays, hash maps and monotonic stacks.
After this lesson you should be able to
- Say what a BST gives you that a hash map does not.
- Use a heap for the top- and streaming-median problems.
- Choose a structure for range queries with updates.
Hash maps answer "is this key present" and nothing else. The moment a question involves order — the smallest, the next one up, everything in a range — you need a tree or a heap, and which one depends on whether you need the whole order or only the extreme.
Proposition 3.1
What a BST buys over a hash map
Ordered operations: find the smallest key above a value, iterate in sorted order, count everything in a range. All are in a balanced tree and impossible in a hash map, which is exactly the trade for its constant-time lookup.
Holds when
- An unbalanced BST degenerates to a list on sorted input — hence AVL, red-black and treaps.
- In-order traversal yields sorted output, which is often the whole reason to use one.
- An order book’s price levels are the canonical financial example, though a fixed tick grid lets an array beat it.
Proposition 3.2
Heaps
A binary heap keeps the minimum at the root with insert and extract, stored as a flat array with no pointers at all. It gives you the extreme element cheaply and tells you nothing about the rest of the order, which is precisely the trade that makes it faster than a tree.
Holds when
- Building a heap from items is , not — the analysis is a standard interview follow-up.
- Finding an arbitrary element is ; use a tree if you need that.
- Two heaps facing each other — a max-heap of the low half and a min-heap of the high — maintain a streaming median.
Why a bounded heap beats sorting. To keep the largest of a stream, hold a *min*-heap of size : the root is the weakest survivor, so each new element is compared against it and either discarded or swapped in. The heap never grows past , so the space is and each step costs rather than . Sorting would need every element in memory and time — and on a genuine stream it is not available at all. The counter-intuitive part is using a min-heap to track maxima, and it is the whole trick.
The rest of this lesson is in Premium
You have read the opening. 12 more sections follow, including 4 worked examples and 3 quick checks.
Nothing is charged for 7 days, and you can cancel before then. Or read Complexity: reading it off, and deriving it in full, free.