Watch an algorithm think
The algorithms and data structures a coding interview expects, one action at a time. Each step shows the line of code it runs, the variables it changed and what it has cost against its bound, and you can bring your own input.
Quick sort
Start with the array 38, 12, 71, 25, 90, 7, 56, 43, 19, 64, 30, 82.
The learning path
58 pages in 17 topics, in the order they build on each other.
Complexity
How the work grows as the input grows: the language every other page uses.
Arrays
Contiguous slots: instant access by index, and a plan for when they fill up.
Hashing
Turn a key into a slot number; the interesting part is what happens when two keys collide.
- Hash table: separate chainingKeys that collide share a bucket and line up in a chain.
- Hash table: linear probingKeys that collide take the next free slot, so clusters form and grow.
- Hash table: rehashing to growLinear probing that doubles the table before it gets crowded, moving every key to its new home.
Stacks and queues
Last in, first out against first in, first out: the two orders much else is built on.
- StackPush and pop at the same end: the last value in is the first value out.
- QueueJoin at the rear, leave from the front: the first value in is the first value out.
- Next greater element (monotonic stack)Keep a stack of values still waiting for something bigger; each value is pushed and popped once.
- Circular buffer (ring queue)A queue in a fixed ring of slots: head and tail chase each other round, and nothing ever moves.
- Deque (circular buffer, both ends)A ring buffer with two moving ends: add or remove at the front or the back in O(1).
Linked lists
Values joined by pointers. Watch the arrows, not the boxes.
- Insert into a sorted linked listWalk to the last smaller node, then relink two pointers. No values move.
- Delete from a linked listPoint the previous node past the one you remove.
- Detect a cycle (tortoise and hare)Two pointers, one twice as fast: if the list loops, the fast one catches the slow one.
- Merge two sorted listsRepeatedly take the smaller of the two heads; attach whatever is left at the end.
- Reverse a linked listTurn every arrow around with three pointers and no extra memory.
- LRU cache (doubly linked list + map)A map finds any key's node at once; a doubly linked list keeps them in order of use.
Two pointers
Walk inwards from both ends, moving whichever pointer can only help.
Sliding window
Keep a running answer for a range, adding what enters and removing what leaves.
Sorting
Put values in order, and count what it costs: comparisons, swaps and writes.
- Bubble sortSwap neighbours that are out of order until a pass makes no change.
- Insertion sortGrow a sorted prefix by inserting each value where it belongs.
- Merge sortSplit in halves, sort each half, then merge the sorted halves.
- Selection sortFind the smallest value left and swap it to the front, one place at a time.
- Quick sortPick a pivot, move smaller values left of it, then sort each side.
- Heap sortBuild a max-heap in the array, then keep moving its top to the end.
- Compare two sortsRace any two of them on the same values and watch the counters.
Searching
Find a value without looking at everything: rule out half the array at a time.
- Search a rotated sorted arrayA sorted array, rotated: one half is always in order, so you can still halve the search.
- Integer square root (search the answer)Search the answers, not an array: halve the range of k until k² is as big as it can be.
- Binary searchHalve the range still in play at every step until the target is found or ruled out.
Trees
Hierarchies you can search in O(log n) when they stay balanced, and O(n) when they do not.
- Binary search tree: insertEach value walks down, left if smaller, right if not, until it finds an empty spot.
- In-order traversalLeft subtree, the node, right subtree: on a search tree this reads the values in sorted order.
- Pre-order traversalThe node first, then its subtrees: the order you would copy a tree in.
- Post-order traversalBoth subtrees first, then the node: the order you would delete a tree in.
- Level-order traversalLevel by level with a queue: breadth-first search on a tree.
- Binary search tree: deleteThree cases: a leaf goes, a single child moves up, two children borrow the successor's value.
- Lowest common ancestor (BST)Walk down from the root until the two values stop being on the same side.
Heaps
A tree kept in an array, where every parent beats its children: the minimum is always on top.
Tries
Words stored letter by letter, so words with the same prefix share a path.
Graphs
Nodes and edges: search them breadth-first or depth-first, order them, find shortest paths, group them.
- Breadth-first searchExplore in rings of distance with a queue: the first time you reach a node is by a shortest route.
- Depth-first searchGo as deep as you can before backing up; the call stack remembers the way back.
- Topological sort (Kahn)Order tasks so every arrow points forward; if that is impossible, there is a cycle.
- Dijkstra's shortest pathsSettle the closest unsettled node, then see if going through it shortens anything else.
- Union-find (disjoint sets)Keep groups as trees; joining two groups points one root at the other, and finding flattens the path.
- Shortest path on a grid (BFS)BFS on a grid: distances spread out in waves from S, and the first wave to touch E gives the shortest path.
- Adjacency list vs matrixThe same graph as lists of neighbours and as a grid of 0s and 1s, built edge by edge.
Backtracking
Try a choice, explore everything it leads to, then undo it and try the next: a tree of recursive calls.
- Subsets (include or skip)For each value, branch twice: take it or skip it. Every leaf of the tree is one subset.
- Permutations (choose, explore, undo)Choose any unused value, recurse, then undo the choice and try the next one.
- N-QueensPlace one queen per row; when a row has no safe square, take back the queen above and move it on.
Dynamic programming
Solve each smaller problem once, keep the answer, and build bigger answers out of it.
- Fibonacci 1: plain recursionThe textbook definition, run as written: the same calls happen again and again.
- Fibonacci 2: memoised recursionSame recursion, but each answer is saved; a repeat call is a lookup instead of a subtree.
- Fibonacci 3: bottom-up tableTurn it around: fill the answers from the bottom up, each from the two before it.
- Coin change (fewest coins)Fewest coins for every amount from 0 up: each amount is one coin more than some smaller amount.
- Longest common subsequenceA table over every pair of prefixes: a shared letter extends the diagonal, otherwise keep the better neighbour.
- 0/1 knapsackAdd the items one row at a time; each cell chooses between leaving the item and taking it with less room.
Greedy
Make the choice that looks best right now and never revisit it; it works when you can prove it does.
Intervals
Ranges on a timeline: sort them by start or end, then sweep once.