Workbench / Volume 1 Companion: Foundations of Computing
V1·04
Algorithms
Companion to Volume 1, chapter 04: how measuring, sorting, design techniques and graph algorithms connect; new angles (a 20-questions game that proves the sorting lower bound, India's population as n, getting dressed as a topological sort, ripples on a lake as Dijkstra); what the chapter simplifies, from Java's sort landing within 0.8% of the theoretical minimum to a knapsack that slows 100× when money is counted in paise; the theory behind it (pseudo-polynomial time, the word-RAM model, reductions, correctness proofs); the JDK's TimSort and dual-pivot quicksort source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 04 has four strands. Measuring gives the vocabulary for cost. Searching and sorting are the algorithms everything else leans on. Design techniques are ways of finding an algorithm for a new problem. Graph and string algorithms are the classic results those techniques produced.
The links worth remembering:
- The techniques recur inside the classics. Merge sort is divide and conquer. Dijkstra and both spanning-tree algorithms are greedy algorithms with a proof that the greedy choice is safe. Bellman–Ford and Floyd–Warshall are dynamic programs. Knowing the technique lets you rebuild the algorithm when you've forgotten it.
- Lower bounds tell you when to stop optimising, and how to cheat. No comparison sort can beat about log₂(n!) comparisons. Counting and radix sort escape the bound by not comparing, which is why library sorts use counting sort inside for small key types.
- "Who picks the input" connects measuring to everything. Quicksort's worst case, a hash table's worst case and a regex's worst case all matter only when an adversary, or unlucky real data, can reach them.
Explain it differently
1. The sorting lower bound is a game of 20 questions. Someone shuffles a deck and you must find out the order by asking only "is card i before card j?". There are n! possible orders, and each answer at best halves the possibilities, so you need at least log₂(n!) questions. For a million items that's 18,488,885 questions (computed). Java's Arrays.sort on a million random Integers asked 18,640,524, less than 1% above the theoretical minimum (measured; Gaps 1). Sorting is one of the few problems where the library is provably almost perfect.
2. Make n the population of India. With n = 1.43 billion and a computer doing 10⁹ simple steps a second:
| Cost | Steps | Time |
|---|---|---|
| n log₂ n (sort everyone) | 4.35 × 10¹⁰ | 43 seconds |
| n² (compare every pair) | 2.05 × 10¹⁸ | 65 years |
(Computed.) The same task, an O(n²) duplicate check against sorting and scanning neighbours, is the difference between a coffee break and a career. That's what "it doesn't scale" means.
3. Recursion is a manager who delegates. A manager asked "how many orders did the whole company take?" doesn't count. They ask each team lead, who asks each team member, and adds up the answers. Each person waits for their reports before answering, and that waiting is the call stack. A deep hierarchy (one manager over one manager over one…) means a very tall stack of people waiting, and the building runs out of floors: a stack overflow (drill D3). Memoisation is the manager writing answers on a whiteboard so the same question is never delegated twice.
4. Dynamic programming is filling in a train timetable. To know the earliest you can reach Vijayawada, you don't try every route from Hyderabad. You fill in, station by station, the earliest arrival at each, using only the already-filled-in arrivals at the stations before it. The state is "earliest arrival at this station"; the transition is "best of the trains coming in". The table is the algorithm. And the size of the table is its cost, which is why counting money in paise instead of rupees made a knapsack 100× slower (Gaps, theoretical 1).
5. A greedy algorithm is hiking downhill in fog. You can only see a few metres, so you always step in the steepest downward direction. On a smooth valley that takes you to the bottom. On a mountain range it strands you in the first dip you find. Greedy algorithms are correct only when the problem has no false dips, and the exchange argument in the chapter is the proof that there are none. Without that proof, a greedy algorithm is a heuristic.
6. Topological sort is getting dressed. Socks before shoes, shirt before tie, trousers before belt and shoes. Any order that respects every "before" works: there are many correct ones. If someone adds "shoes before socks", there's a cycle and no order exists. Build systems, course prerequisites, kitchen prep steps (Chapter Exercises P8) and database migrations are all getting dressed.
7. Dijkstra is a ripple on a still lake. Drop a stone at the start: the ripple reaches nearby points first, then farther ones, always in order of distance. Each point is "settled" the moment the ripple touches it, because nothing can reach it sooner. A negative edge is a tunnel that lets the water arrive somewhere earlier than the ripple, after that point was already settled, and the whole logic breaks (the chapter's lab shows it).
8. Big-O is about the shape of a curve, measured by a ruler with no units. O(n) and O(n log n) say how the cost bends as n grows, never what it costs at n = 50. That's why insertion sort is inside every library sort for small pieces: at n ≤ 32 (TimSort) or 44 (dual-pivot quicksort), its tiny constant beats everyone's better curve (Code walkthrough).
Gaps and misconceptions
What the chapter oversimplifies
1. "Comparison sorts need Ω(n log n) comparisons": the real numbers are more interesting. The chapter states the bound. Here it is measured against Java's TimSort, counting every call to the comparator (JDK 21, one million Integers):
n = 1,000,000, lower bound log2(n!) = 18,488,885 comparisons
random: 18,640,524 comparisons
sorted: 999,999 comparisons
reversed: 999,999 comparisons
10 runs: 4,599,994 comparisons
Two lessons. On random data TimSort is within 0.8% of the information-theoretic minimum: you will not out-sort it by cleverness. And on sorted or reversed data it uses n − 1 comparisons, below the "lower bound". That's not a contradiction: the bound is for the worst case over all inputs. Real data is rarely random (timestamps arrive nearly sorted, a day's orders are concatenated sorted batches), and an adaptive sort exploits that: ten pre-sorted runs cost a quarter of random input.
2. "Each comparison is O(1)." Comparing two ints is. Comparing two strings costs up to the length of their common prefix, so sorting IDs like tiffinbox-order-2026-11-14-kitchen-0007-000123456 does more work per comparison than sorting the same digits placed first:
500,000 strings of equal length: shared 40-char prefix 329 ms vs differing at the start 262 ms
Only 26% slower here, because the JDK compares Latin-1 strings with ArraysSupport.mismatch, an intrinsic the JIT can turn into wide vector comparisons. In languages or data without that help (UTF-16 strings, composite keys compared field by field, Comparator.comparing(...).thenComparing(...) chains), comparison cost multiplies the whole sort. When sorting by a derived or expensive key, compute it once per element first (the "decorate, sort, undecorate" pattern; Python's key= does this for you).
3. "Recursion depth O(n) will overflow somewhere around 10⁴ to 10⁶ frames." The chapter's range is right, and the bottom of it arrives sooner than people expect. A plain recursive DFS over a chain of nodes, in Java with default settings on this machine:
chain of 1000: visited 1000
chain of 10000: StackOverflowError at depth 5364
chain of 100000: StackOverflowError at depth 5365
About 5,400 levels, because each level holds several frames (the method, HashMap.getOrDefault, the iterator) and frames for code that hasn't been JIT-compiled yet are large. Raising the stack to 16 MB (-Xss16m) only moved it to 94,733. Python's default limit is 1,000 frames: a memoised recursive function failed just above n = 999 in a test here, exactly like the unmemoised one (drill D4). For anything whose depth grows with the data (a chain of referrals, an org chart, a category tree a customer can nest), use an explicit stack.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "An O(n log n) algorithm is always faster than an O(n²) one." | Only beyond some n. Library sorts use insertion sort below 32–44 elements. | Chapter Exercises P2; Code walkthrough |
| "Sorted input is the worst case for quicksort." | For naive first-element pivots. Library quicksorts choose pivots from samples and fall back to heapsort; TimSort is fastest on sorted input. | Gaps 1; Code walkthrough |
| "A DP solution is polynomial." | It's polynomial in the table size, which may be exponential in the input's length. | theoretical gap 1 |
| "If the heap holds an object, updating the object updates the heap." | The heap doesn't know you changed it; order breaks silently. | drill D1 |
"binarySearch returns −1 when not found." |
It returns -(insertion point) - 1, which is −1 only when the key would go first. Any negative means not found. |
drill D2 |
| "Memoisation makes recursion safe." | It removes repeated work, not depth. | drill D4 |
Theoretical gaps: the ideas behind the chapter
1. Pseudo-polynomial time: why "O(n·W)" can be exponential. The chapter's 0/1 knapsack runs in O(n·W) for n items and capacity W. That looks polynomial, but complexity is measured against the size of the input, and writing down W takes only log₂ W digits. Double the digits of W and the table squares. Real measurement, the same 30 dishes and the same ₹1,000 budget:
30 dishes, budget 1000 rupees, counted in rupees: 1,001 columns, best rating 58, 1 ms
30 dishes, budget 1000 rupees, counted in paise: 100,001 columns, best rating 58, 133 ms
Same problem, same answer, 100× slower, purely from the unit of money. That's pseudo-polynomial time: polynomial in the value of W, exponential in its length. It's also why knapsack is NP-hard and yet solved daily: when the numbers are small, the DP is fine. In TiffinBox, prices in paise (stage 2's rule) are right for arithmetic and wrong as a DP dimension; scale down (to rupees, or ₹10 steps) where exactness isn't needed.
2. The model of computation decides what "fast" means. Big-O counts "steps", which presumes a model of what one step is. The usual one is the word RAM: arithmetic on machine-sized integers and access to any memory cell each cost one step. Under that model, radix sort sorts n 64-bit integers in O(n), "beating" n log n, because it uses the bits of the key directly. Under the comparison model, where the only operation is "compare two keys", it isn't even allowed. Lower bounds are always relative to a model, so a lower bound is a statement about a kind of algorithm, not about the problem.
3. Correctness is a proof, and tests sample it. The chapter introduces loop invariants for binary search. The general method is three obligations: the invariant holds initially, each step preserves it, and when the loop stops the invariant plus the stopping condition imply the answer. Add a variant (a quantity that strictly decreases, like hi - lo) and you've proved termination too. Senior engineers rarely write these proofs out, but they think in them during review: "what's true at the top of this loop?" catches off-by-one errors faster than any test.
4. Reductions: solving a new problem by recognising an old one. "Schedule kitchen prep so no step starts before its inputs are ready" is topological sort. "Find the cheapest set of delivery zones that covers every customer" is set cover (NP-hard). Transforming a new problem into a known one is a reduction, and it works in both directions: reducing to a solved problem gives you an algorithm; reducing a known hard problem to yours proves yours is hard, so you stop looking for an exact fast algorithm (Chapter Exercises S4).
5. Average case needs a probability distribution, and you rarely have one. "Quicksort is O(n log n) on average" means: averaged over all n! orderings, equally likely. Real inputs aren't uniformly random: they're sorted, nearly sorted, full of duplicates, or chosen by someone. Randomised algorithms move the randomness from the input into the algorithm (a random pivot), so the guarantee holds for every input, in expectation over the algorithm's own coin flips. That's a much stronger promise, and the reason "expected" and "average" are not synonyms.
6. Online against offline. Most of the chapter's algorithms are offline: they see all the input first. Many real problems are online: orders arrive one at a time and the kitchen must decide now. An online algorithm is judged by its competitive ratio, how much worse it does than the best offline solution with hindsight. The kitchen queue in the TiffinBox build is an online scheduler, and "earliest pickup first" is a classic online rule.
Applying it
Code walkthrough
The chapter's table names the algorithms behind Java's sorts. Here is how they're built. Excerpts from jdk-21-ga.
TimSort: finding the order that's already there
java/util/TimSort.java sorts objects for Arrays.sort(T[], Comparator), List.sort and Collections.sort. It starts by finding runs:
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
Comparator<? super T> c) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
}
This is why sorted and reversed inputs cost exactly 999,999 comparisons: the whole array is one run, found by walking it once (and reversing it in place if descending). One subtle detail: a descending run must be strictly descending (< 0), while an ascending run may contain equal elements (>= 0). Reversing a run containing equal elements would swap their order and break stability, so equal neighbours always end a descending run.
Short runs are extended to a minimum length with insertion sort, and that length is chosen carefully:
private static int minRunLength(int n) {
assert n >= 0;
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
With MIN_MERGE = 32, this returns a run length between 16 and 32 such that n divided by it is a power of two or just below one. Merges are most efficient between runs of equal size (like a balanced tournament), so choosing the run length to split n into a power of two of equal pieces keeps every merge balanced. Then runs are merged, and when one run keeps "winning" (MIN_GALLOP = 7 times in a row), TimSort switches to galloping: exponential then binary search to find how many elements to copy at once. That's what turns "10 sorted runs" into 4.6 million comparisons instead of 18.6 million.
DualPivotQuicksort: quicksort that can't go quadratic
java/util/DualPivotQuicksort.java sorts primitive arrays (Arrays.sort(int[])). Inside its main loop, three safety nets appear in order:
/*
* Invoke insertion sort on small leftmost part.
*/
if (size < MAX_INSERTION_SORT_SIZE) {
insertionSort(a, low, high);
return;
}
/*
* Check if the whole array or large non-leftmost
* parts are nearly sorted and then merge runs.
*/
if ((bits == 0 || size > MIN_TRY_MERGE_SIZE && (bits & 1) > 0)
&& tryMergeRuns(sorter, a, low, size)) {
return;
}
/*
* Switch to heap sort if execution
* time is becoming quadratic.
*/
if ((bits += DELTA) > MAX_RECURSION_DEPTH) {
heapSort(a, low, high);
return;
}
with
private static final int DELTA = 3 << 1;
private static final int MAX_RECURSION_DEPTH = 64 * DELTA;
Read it as the chapter's three ideas, combined:
- Small pieces: insertion sort. Big-O loses to constants at small n (Explain it differently 8).
- Nearly sorted input: merge the runs. The same insight as TimSort, applied to primitives.
- Too deep: heapsort.
bitsgrows by 6 per level of partitioning; after 64 levels, the remaining piece is heapsorted. Quicksort's O(n²) worst case needs deep, lopsided partitioning, so capping depth caps the cost at O(n log n). This is the introsort idea (C++'sstd::sortuses it too): run the fast-on-average algorithm, and switch to the guaranteed one when the input turns out to be adversarial.
The same file also uses counting sort for byte[] arrays of 64 or more elements, and for short[] and char[] of 1,750 or more (MIN_BYTE_COUNTING_SORT_SIZE, MIN_SHORT_OR_CHAR_COUNTING_SORT_SIZE): with at most 256 or 65,536 possible values, counting beats comparing.
Read it yourself
- Why do primitives get an unstable quicksort, while objects get a stable merge sort?
- TimSort's descending-run check uses
< 0. Construct a three-element input where using<= 0would produce an unstable result.
Debugging drills
D1. A route planner that sometimes picks a longer route
A Dijkstra implementation keeps Node objects in a PriorityQueue ordered by dist. When it finds a shorter path, it updates node.dist in place. A minimal reproduction:
Node a = new Node("A", 50), b = new Node("B", 20), c = new Node("C", 40), d = new Node("D", 30);
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingLong(n -> n.dist));
pq.addAll(List.of(a, b, c, d));
c.dist = 5; // found a shorter path to C: update in place
after setting C to 5 in place, polled: [B=20, C=5, D=30, A=50]
C should have come out first. Explain, and give two correct fixes.
D2. "Dish not found", for a dish that's on the menu
List<Dish> menu = /* d4 Idli, d1 Vada, d9 Dosa, d2 Pongal, d7 Upma */;
menu.sort(Comparator.comparing(Dish::name));
int i = Collections.binarySearch(menu, new Dish("d1", null), Comparator.comparing(Dish::id));
menu sorted by name: [d9, d4, d2, d7, d1]; binarySearch for d1 by id: -1
d1 is in the list. Why −1, and what's the general rule?
D3. Deleting a category crashes the admin panel
An admin can nest menu categories ("South Indian › Breakfast › Dosas › Specials …"). Deleting one deletes its children with a recursive method. It worked for years; then an import script created a chain of 10,000 nested categories, and deleting the top one threw StackOverflowError. The same recursion, measured:
chain of 10000: StackOverflowError at depth 5364
Fix it without raising -Xss.
D4. Memoised, and still crashing
A Python service computes "number of ways to compose a thali of n items" with a memoised recursion:
@functools.lru_cache(maxsize=None)
def ways(n):
return 1 if n < 2 else ways(n-1) + ways(n-2)
recursion limit: 1000
ways(500) has 105 digits
ways(5000): RecursionError: maximum recursion depth exceeded
The developer says "but it's memoised, so it's O(n)". Explain, and fix it.
Career-oriented
Interview prep
Mid level
Q1. Given a day's orders (up to 2 million) with timestamps, find whether any two orders from the same customer are less than 60 seconds apart. Give an algorithm and its complexity.
How to get there. Say the naive version first (all pairs, O(n²)), then ask what structure makes the comparison local. Sorting puts candidates next to each other; grouping puts each customer's orders together. Then state the cost and the memory, and handle edge cases (equal timestamps, one order per customer).
Q2. Explain why Dijkstra's algorithm is correct, in under two minutes.
How to get there. Interviewers want the invariant, not the code. State it (every settled node has its true shortest distance), say why the next popped node must be correct (any other path to it would pass through an unsettled node at least as far away, and with non-negative edges can't get shorter), and finish with what breaks it (negative edges).
Senior level
Q3. A nightly batch job that recommends dishes to each customer has gone from 20 minutes to 7 hours over two years, while customers grew 4×. What happened, and how do you investigate?
How to get there. Use the growth numbers as evidence: 4× data, 21× time is close to 4² = 16× plus overhead, which suggests something quadratic. Then a structured investigation: profile, find the hot loop, identify the hidden pair-wise work, fix with an index or sort, and protect against regression with a scaling test.
Q4. Product wants "the 10 most similar dishes" for each of 50,000 dishes, refreshed hourly. How do you design it?
How to get there. Size the naive version first (all pairs), then reduce the candidates, then choose where the computation runs and how results are stored. Discuss exact against approximate and what "similar" costs to compute.
Staff level
Q5. Your organisation has three different implementations of "delivery ETA" across services, each with its own shortest-path code, and they disagree. How do you resolve it?
How to get there. This is about ownership and correctness at scale, not Dijkstra. Spine: measure the disagreement, find the root causes (data, algorithm, assumptions), pick one source of truth with an owner, migrate with a comparison period, and put guardrails in place.
Q6. An engineer proposes an exact optimiser to assign 5,000 orders to 800 delivery partners every 30 seconds. How do you evaluate the proposal?
How to get there. Recognise the problem class (assignment with constraints, vehicle routing), know which parts are polynomial and which are NP-hard (theoretical gap 4), and turn "exact" into a requirements question: how good must it be, how fast, and what happens when it doesn't finish.