Workbench / Volume 1 Companion: Foundations of Computing
V1·03
Data Structures
Companion to Volume 1, chapter 03: how linear, keyed and on-disk structures connect; new angles (a coat-check counter, a tournament bracket, the hospital triage desk, Hyderabad's metro map, and the arithmetic of a billion keys in four disk reads); what the chapter simplifies, from Java's HashMap turning colliding buckets into trees (3,170 ms against 2 ms) to PriorityQueue printing in "the wrong order", and the theory behind it (abstract types against implementations, amortised cost, lower bounds and why hashing escapes them); the JDK's HashMap and PriorityQueue source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 03's structures fall into three families. Linear structures keep items in sequence and differ in how you're allowed to reach them. Keyed and ordered structures find items by a key, either by hashing it or by comparing it. Advanced and on-disk structures trade exactness, memory or write speed for something specific: "probably not present", "connected or not", "one disk page per node".
The links worth remembering:
- Almost everything is an array underneath. Hash tables are an array of buckets, heaps are a tree stored in an array, and dynamic arrays are arrays that copy themselves. That's why the memory cost model (contiguous is fast, pointer-chasing is slow) decides real performance more often than Big-O does.
- Two ways to find a key: hash it or compare it. Hashing gives O(1) on average but no order. Comparing gives O(log n) and sorted order, ranges and "nearest". Most "which structure?" questions come down to whether you need order.
- B-trees are balanced trees reshaped for the cost model of disks. Same idea as a red-black tree; the node is a disk page instead of a few bytes, so the tree is short and wide.
Explain it differently
1. A hash table is a coat-check counter. You hand over your coat; the attendant hangs it on hook 47 and gives you token 47. Later, the token takes the attendant straight to the hook, without searching the room. The hash function is the rule that turns your coat into a hook number. Collisions happen when two coats map to the same hook: the attendant hangs both there (separate chaining) or tries the next free hook (open addressing). As the cloakroom fills, every hook gets crowded and finding a coat slows down, so before it gets too full (the load factor, 75% in Java) the attendant moves everything to a bigger room. That move is the occasional slow put hidden inside "O(1) on average".
2. A binary search tree is a tournament bracket read backwards. To find whether "Pongal" is on the menu, start at the top: is it before or after "Idli"? After. Before or after "Sambar"? Before. Each comparison discards half of what's left, like each round of a knockout tournament halving the players. A balanced tree is a fair bracket: about log₂ n rounds. An unbalanced one, built from already-sorted names, is a "bracket" where one player plays every match in a row: n rounds, no faster than a list (Chapter Exercises P6 measures it).
3. A heap is a hospital triage desk. Patients don't leave in arrival order; the most urgent is always seen next. The triage nurse doesn't keep the whole waiting room sorted (too much work). They only guarantee one thing: the most urgent patient is at the front. When someone new arrives, they're compared upwards just enough to find their place relative to the front (log n comparisons). That partial order is why a heap is fast, and also why printing a Java PriorityQueue doesn't show the patients in order (drill D1).
4. A trie is a phone's predictive keyboard. Type p, and the keyboard narrows to words starting with p; type po, narrower still. Each letter moves one step down a tree of letters, and the cost depends only on how many letters you've typed, never on how many words the dictionary holds. That's the trie's promise: lookup cost proportional to the key's length, not the collection's size. The TiffinBox build (stage 3) shows the catch: reaching the right node is instant, but if a million dishes sit under p, collecting and sorting them isn't.
5. A graph is the Hyderabad metro map. Stations are vertices; tracks are edges. An adjacency list is each station's sign listing the stations you can reach directly; an adjacency matrix is the big fare table with every station along both axes, mostly empty because most pairs aren't directly connected. Real networks (metro lines, roads, friendships) are sparse: a station touches 2–4 others out of dozens, so lists win. The matrix only pays off when nearly everything connects to nearly everything.
6. A Bloom filter is a bouncer with a fuzzy memory. The bouncer can't remember every guest's face, but remembers a few features of each ("tall, glasses, red shirt"). If someone has none of the remembered combinations, they definitely weren't on the list: turn them away without checking the guest book. If they match, they might have been: go and check the book. The bouncer never wrongly turns away a real guest (no false negatives), but sometimes sends someone to the book unnecessarily (a false positive). The trade: a tiny memory in exchange for skipping most expensive lookups.
7. The arithmetic that makes databases fast. How many steps to find one key among a billion?
| Method | Steps for 1,000,000,000 keys |
|---|---|
| scan a list | up to 1,000,000,000 comparisons |
| balanced binary tree | log₂(10⁹) ≈ 29.9, so about 30 comparisons |
| B-tree with 500 keys per node | log₅₀₀(10⁹) ≈ 3.33, so 4 node reads |
| hash table | about 1–2 probes on average |
(The logarithms were computed, not estimated.) A B-tree reads one node per level, and each node is one disk page. Four page reads, and the top two levels are almost always cached in memory, so finding one row among a billion costs about one or two real disk reads. That one table explains why every relational database indexes with B+ trees (Volume 4).
8. Big-O is how a cost grows, not what it costs. O(1) means "doesn't grow with n", not "fast". Hashing a 2,000-character string is O(1) with respect to the table's size and still slower than comparing two small integers 30 times. When two structures have different Big-O, it tells you who wins eventually. When n is small, or the constant is a cache miss against a register read, measure. Chapter Exercises T2 and P1 do exactly that.
Gaps and misconceptions
What the chapter oversimplifies
1. "Hash tables: O(n) worst case under bad hashing or attack." In Java, not since Java 8. When one bucket's chain grows past 8 entries (in a table of at least 64 buckets), HashMap converts that bucket into a red-black tree, so the worst case becomes O(log n), if the keys are Comparable. If they aren't, the tree can't order equal-hash keys and lookups degrade back to a scan. Real measurement (JDK 21): 20,000 keys that all return hashCode() == 42, each looked up once:
20,000 keys, all with hashCode 42: lookups of every key took 3170 ms (not Comparable) vs 2 ms (Comparable)
The same horrible hash function, and a 1,500× difference, purely from whether the key type implements Comparable. So the chapter's "O(n) worst case" is right for many languages and for Java with non-comparable keys. A senior takeaway: make key types Comparable (records of strings and numbers easily can), and the worst case of your maps is bounded. The Code walkthrough shows the JDK code that makes the difference.
2. "Heaps give the minimum in O(1)": true, but a heap isn't sorted. People take "priority queue" to mean "a sorted queue". Real output:
PriorityQueue printed: [10, 20, 40, 50, 30]
polled one by one: [10, 20, 30, 40, 50]
toString, iteration and streams walk the underlying array, which is only heap-ordered (each parent smaller than its children). Only repeated poll() gives sorted order. It's also not stable: equal priorities don't come out in insertion order (the TiffinBox build, stage 3, shows six orders with the same pickup time served as o1, o6, o5, o4, o3, o2).
3. "Hash tables need correct equality" understates what ordered structures need. The chapter's equality contract is about equals and hashCode. A TreeMap or TreeSet doesn't call equals at all: it uses the comparator, and treats two items as the same if the comparator returns 0. Sort dishes by price, and two dishes with the same price collapse into one (real output):
TreeSet by price, 3 dishes added: size 2 [Dish[name=idli, paise=4000], Dish[name=dosa, paise=8950]]
contains vada? true | contains ("poha", 4000)? true
vada was silently dropped, and the set now claims to contain a poha that was never added. The Javadoc calls this a comparator that is "not consistent with equals". The fix is to break ties on a unique field (comparingInt(Dish::paise).thenComparing(Dish::name)), the same idea as the queue's sequence number in the TiffinBox build.
4. "Multi-dimensional arrays" in Python aren't what they look like. The chapter describes 2-D arrays as rows of cells. Python's quickest-looking way to build one makes every row the same list:
[[0]*3]*3 after grid[0][0]=9: [[9, 0, 0], [9, 0, 0], [9, 0, 0]]
comprehension version: [[9, 0, 0], [0, 0, 0], [0, 0, 0]]
[row] * 3 copies the reference three times (chapter 02's aliasing, in a data structure). The comprehension builds three separate lists.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "O(1) means fast." | It means the cost doesn't grow with n. Hashing a long key, or a cache miss, can make an O(1) step slower than several O(log n) ones. | Explain it differently 8; Chapter Exercises T2 |
| "A trie makes prefix search instant." | Reaching the prefix's node is instant; collecting and sorting everything under it isn't. | the TiffinBox build, stage 3: 732 ms down to 0.3 ms after pre-sorting |
"A PriorityQueue is a sorted list." |
It's heap-ordered and unstable. | gap 2 above |
| "Sorted means numeric order." | A TreeMap<String, …> sorts k12 before k7, character by character. |
the TiffinBox build, stage 3 |
"Arrays.asList turns any array into a list." |
Not a primitive array: Arrays.asList(int[]) is a list of one element, the array itself. |
drill D3 |
"A subList is a smaller list." |
It's a view of the original: it shares storage, keeps the whole original alive, and breaks if the original is structurally modified. | drill D4 |
| "Bloom filters never give false negatives." | True only if items are never removed. Deleting by clearing bits creates false negatives; counting Bloom filters exist for that. | chapter, "Bloom filters" |
Theoretical gaps: the ideas behind the chapter
1. An abstract data type is a promise; a data structure is how you keep it. The chapter mixes the two, which is natural, but the distinction is the key to designing with them. A map (an abstract data type) promises "put, get, remove by key". A hash table, a red-black tree and a sorted array are three implementations of that promise with different costs and extra abilities (order, ranges). Program against the abstract type (Map, Deque), choose the implementation by the operations you need, and you can swap it later without touching callers. Java's collection interfaces are this idea, and so are Volume 3's repositories.
2. Amortised cost is an average over time, not over inputs. "Dynamic arrays append in amortised O(1)" doesn't mean "usually O(1)". It means any sequence of n appends costs O(n) in total, even though an individual append occasionally copies everything. The proof idea (the potential method): each cheap append "pays forward" a little credit, which covers the next expensive copy. Two consequences the chapter doesn't spell out:
- amortised bounds say nothing about one operation's latency. A resize of a 10-million-entry
HashMapis one slow request in a latency-sensitive service; - presizing (
new HashMap<>(expected * 4 / 3 + 1),new ArrayList<>(n)) removes those spikes when you know the size, as the TiffinBox menu does.
3. Lower bounds: why O(log n) is the best comparison can do, and how hashing cheats. Any method that finds a key only by comparing keys needs at least log₂ n comparisons in the worst case: each comparison answers one yes/no question, and you must distinguish n possibilities (chapter 01's companion, "bits as yes/no questions"). So balanced trees are optimal among comparison-based structures. Hashing escapes the bound by not comparing at all: it computes where the key is. The price is losing order: a hash table can't answer "next larger key" or "everything between A and B". The same argument proves sorting by comparison needs Ω(n log n), and it's why counting sort and radix sort can be faster: they don't compare (chapter 4).
4. Expected against worst case, and who chooses the input. Hash tables are O(1) expected, assuming the keys behave as if random relative to the hash function. That assumption fails when an adversary chooses the keys (hash flooding, covered by the exercises) or when real data has patterns your hash doesn't spread (consecutive Floats, as the HashMap source comment notes). Senior engineers ask of every structure: what's the worst input, can someone outside choose it, and what bounds the damage (randomised seeds, treeified buckets, input limits)?
5. Every structure trades space, time and generality. The chapter's decision guide lists operations. The underlying principle: you can usually buy speed with memory (indexes, pre-sorted trie nodes, caches), memory with time (compression, Bloom filters), or both with generality (specialised structures like Fenwick trees that answer exactly one kind of question). Naming which of the three you're spending makes design reviews faster: "this index costs 300 MB to make that query 1,000× faster" is a decision someone can approve.
6. The memory hierarchy is part of the cost model. Big-O counts operations as if every memory access cost the same. On real hardware, an access that hits the CPU cache costs about 1 ns, and one that goes to RAM about 100 ns (chapter 01's companion, Explain it differently 5). That's why the chapter's lab finds arrays beating linked lists even for "O(1) insert" workloads. Cache-oblivious and cache-aware structures (B-trees in memory, van Emde Boas layouts) are designed around this. Chapter 7 makes it concrete.
Applying it
Code walkthrough
Two JDK classes contain most of this chapter in production form. Excerpts from jdk-21-ga.
HashMap: spreading hashes, chaining, and turning chains into trees
java/util/HashMap.java. First, the constants and the hash "spreader":
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
The bucket index is (n - 1) & hash, the low bits of the hash, because the table size n is a power of two. A hashCode whose variety is all in the high bits would put every key in the same few buckets. h ^ (h >>> 16) folds the high 16 bits into the low 16, cheaply. The source comment explains the choice:
Because the table uses power-of-two masking, sets of hashes that vary only in bits above the current mask will always collide. (Among known examples are sets of Float keys holding consecutive whole numbers in small tables.) …we just XOR some shifted bits in the cheapest possible way…
Then the heart of put:
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
...
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
Read it against the chapter:
- An empty bucket gets a new node: the O(1) case.
- Otherwise it walks the chain (separate chaining), comparing the stored hash first (a cheap
intcomparison) and callingequalsonly when hashes match. That's whyhashCodeandequalsmust agree. - When a chain reaches 8 nodes,
treeifyBinturns it into a tree. It first checksMIN_TREEIFY_CAPACITY: if the table is smaller than 64 buckets, it resizes instead, because in a small table long chains are more likely bad luck than a bad hash.
And the lookup inside a tree bucket, which explains the 3,170 ms against 2 ms measurement:
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
The tree is ordered by hash first. When hashes are equal (every key in the experiment), it tries to order by the key's own compareTo (comparableClassFor checks whether the key's class implements Comparable of itself). If it can, it goes left or right: O(log n). If it can't, it has no way to choose, so it searches the right subtree recursively and then continues left: effectively visiting every node. That one else if is the 1,500×.
PriorityQueue: a binary heap in an array
private static <T> void siftUpComparable(int k, T x, Object[] es) {
Comparable<? super T> key = (Comparable<? super T>) x;
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = es[parent];
if (key.compareTo((T) e) >= 0)
break;
es[k] = e;
k = parent;
}
es[k] = key;
}
The whole tree is the array es. The parent of slot k is slot (k - 1) / 2 (written >>> 1, an unsigned shift). A new element starts at the end and moves up while it's smaller than its parent: at most log₂ n steps. Two details:
if (key.compareTo(e) >= 0) break;stops at equal keys. So equal elements keep whatever positions sifting gives them, and nothing records arrival order. That's the instability in gap 2: the heap simply has no information about who came first.- Parents are moved down (
es[k] = e) rather than swapped, and the new key is written once at the end. Half the writes of the textbook swap version, which matters in the most-called method of every scheduler built on this class.
Read it yourself
- Why does
HashMapcomparee.hash == hashbefore callingequals, whenequalsalone would be correct? - In
siftUpComparable, what would change if>= 0were> 0?
Debugging drills
D1. "The priority queue is broken": the dashboard shows orders out of order
A kitchen dashboard shows waiting orders by printing the queue:
PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(50, 20, 40, 10, 30)); // minutes until pickup
System.out.println("PriorityQueue printed: " + pq);
PriorityQueue printed: [10, 20, 40, 50, 30]
The kitchen manager reports a bug: 30 should come before 40. Is the queue broken? Fix the dashboard without making serving slower.
D2. Dishes disappearing from a price-sorted set
record Dish(String name, int paise) {}
TreeSet<Dish> byPrice = new TreeSet<>(Comparator.comparingInt(Dish::paise));
byPrice.add(new Dish("idli", 4000)); byPrice.add(new Dish("vada", 4000)); byPrice.add(new Dish("dosa", 8950));
TreeSet by price, 3 dishes added: size 2 [Dish[name=idli, paise=4000], Dish[name=dosa, paise=8950]]
contains vada? true | contains ("poha", 4000)? true
Explain both lines, and fix the set so it holds all three dishes in price order.
D3. contains says a price isn't there when it is
int[] prices = {3, 1, 2};
System.out.println("Arrays.asList(int[]).size() = " + Arrays.asList(prices).size() + ", contains(1)? " + Arrays.asList(prices).contains(1));
Arrays.asList(int[]).size() = 1, contains(1)? false
Why is the size 1, and why didn't the compiler stop it?
D4. A sub-list that crashes later, and a memory leak
A report method keeps "the first two orders of the day" for a summary card:
List<Integer> orders = new ArrayList<>(List.of(1, 2, 3, 4, 5));
List<Integer> firstTwo = orders.subList(0, 2);
orders.add(6);
System.out.println(firstTwo);
subList after parent add: ConcurrentModificationException
Explain the exception, then explain a second problem this pattern causes in a long-running server even when nothing is added.
Career-oriented
Interview prep
Mid level
Q1. Explain how a HashMap works, from put to get, and what happens as it fills up.
How to get there. Spine: hash → index → bucket → collision handling → equality → resize → worst case. At each step say what can go wrong. Mention one Java-specific detail (the hash spreader, treeified buckets) to show you've looked inside, not just memorised the textbook.
Q2. You need the 10 most recent orders, out of a stream of millions, at any moment. Which structure, and why?
How to get there. Name the operations and their frequencies first (insert constantly, read top-10 often, never look up arbitrary orders), then match a structure to them. Compare at least two candidates with costs. Watch the definition: "most recent" by arrival is a ring buffer; "highest priority" is a heap.
Senior level
Q3. A service's p99 latency spikes every few minutes, and profiling shows the time in HashMap.resize. Explain why, and what you'd change.
How to get there. Connect amortised cost (theoretical gap 2) to tail latency: amortised O(1) doesn't promise anything about one request. Then give options in order of effort: presize, cap and reuse, change structure, move the work off the request path. End with how you'd verify the fix (measure p99 before and after).
Q4. Your team wants to add an in-memory index to make a slow admin search fast. What do you ask before agreeing?
How to get there. An index is a space-time trade-off with a maintenance cost (theoretical gap 5). Structure the questions: access pattern (which queries, how often), size and growth (memory now and in two years), freshness (how updates reach the index, and what happens on restart), concurrency (readers and writers), correctness (consistency with the source of truth), and alternatives (a database index might be better).
Staff level
Q5. Across 30 services, engineers keep choosing collections badly: unbounded maps as caches, linked lists for queues, contains on lists in loops. How do you raise the baseline?
How to get there. Staff answers change defaults and feedback loops rather than lecturing. Spine: find (profiling and static analysis to locate the patterns), fix the worst (with numbers), make the right thing easy (shared libraries, templates), catch regressions (tooling in CI), teach with evidence (internal write-ups using your own incidents), measure (fewer incidents, lower heap use).
Q6. Design the data structures for an in-memory leaderboard of the top dishes per city, updated by every order (thousands per second), read by every app open.
How to get there. Separate write path and read path, since their rates differ. Pick a structure for counting (hash map of counts), a structure for ranking (a sorted structure or periodic top-k), decide freshness, and consider multiple instances (in-memory per instance against a shared store). Bring numbers: dishes per city, update rate, read rate.