Phase 4: Non-Linear Data Structures
Everything you have built so far has been a line: lists, strings, stacks, queues and linked lists all have a first element, a last element, and one way to walk from one to the other. This phase is about structures that branch. A binary tree splits into two subtrees at every node, a binary search tree keeps those subtrees ordered so you can find things fast, a heap keeps the smallest element ready at the top, and a trie stores words letter by letter along shared branches.
The thread that ties all of them together is recursion. A tree is defined in terms of smaller trees, so the natural way to process one is with a function that calls itself on each subtree. By the end of this phase you will be able to:
- write a recursive function by naming its base case and its recursive step, and know when memoization is needed;
- traverse a binary tree depth-first (recursively and with an explicit stack) and breadth-first (with a queue);
- use the binary search tree invariant to validate, search and select elements;
- solve "top k" and "k-way merge" problems with
heapq; - build a trie out of nested dictionaries.
Recursion
A recursive function solves a problem by solving a smaller instance of the same problem and doing one extra step. Every recursive function has two parts:
- a base case: an input so small the answer is known without any further calls;
- a recursive case: do a little work, then call yourself on something strictly closer to the base case.
def sum_of_digits(n):
if n < 10: # base case: a single digit
return n
return n % 10 + sum_of_digits(n // 10) # one digit + the rest
print(sum_of_digits(1234))
10
It helps to trace the calls by hand. sum_of_digits(1234) cannot answer until sum_of_digits(123) returns, which waits on sum_of_digits(12), which waits on sum_of_digits(1). That last call hits the base case and returns 1; then the waiting calls finish in reverse order: 2 + 1 = 3, 3 + 3 = 6, 4 + 6 = 10.
The call stack
Each unfinished call lives in a frame on the call stack. Python limits how deep that stack can grow; on this site the limit is 6000 frames. Recursing once per element of a large input therefore crashes:
def count_down(n):
if n == 0:
return 0
return 1 + count_down(n - 1)
print(count_down(1000))
print(count_down(100000))
1000
RecursionError: maximum recursion depth exceeded
Two lessons follow. First, if the recursion depth is proportional to the input size, prefer a loop or an explicit stack for large inputs. Second, when you can shrink the problem by half instead of by one, do it: the depth becomes O(log n). Fast exponentiation is the classic example. Since x**8 == (x**4)**2, you can compute power(x, n // 2) once, square it, and multiply by one more x when n is odd. That turns a million multiplications into about twenty.
Memoization
Some recursions are shallow but branch into a huge number of calls, most of which repeat work. The naive Fibonacci definition is the textbook case:
calls = 0
def slow_fib(n):
global calls
calls += 1
if n < 2:
return n
return slow_fib(n - 1) + slow_fib(n - 2)
print(slow_fib(20), calls)
6765 21891
Twenty-two thousand calls to produce a four-digit number, because slow_fib(18) is computed twice, slow_fib(17) three times, and so on down the tree. The fix is memoization: store every result the first time you compute it and look it up afterwards. A dictionary keyed by the argument is all you need, and functools.lru_cache will wrap it for you:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60))
1548008755920
With the cache, fib(60) makes about 120 calls instead of a few trillion. Memoization is the doorway to dynamic programming, which you will meet in Phase 5.
Both functions follow the definition F_0 = 0, F_1 = 1 and F_n = F_{n-1} + F_{n-2} for n \ge 2. The number of calls C_n that slow_fib(n) makes obeys almost the same recurrence, C_n = 1 + C_{n-1} + C_{n-2} (one call for itself plus the calls made by its two halves), so it grows as fast as the Fibonacci numbers themselves, by a factor of about 1.6 for each step of n. With the cache each value is computed once, which takes 2n - 1 calls. Press Run to see the two counts; on the logarithmic y axis exponential growth is a straight line:
plain = [1, 1] # C_0 and C_1
for n in range(2, 31):
plain.append(1 + plain[-1] + plain[-2]) # C_n = 1 + C_(n-1) + C_(n-2)
cached = [1] + [2 * n - 1 for n in range(1, 31)]
plot(range(31), plain, label="without memo", logy=True, xlabel="n", ylabel="calls")
plot(range(31), cached, label="with memo")
The value at n = 20 is 21,891, the count printed above.
Common mistakes
- Forgetting the base case, or writing one that is never reached (for example recursing on
n - 1but checkingn == 0whennstarts negative). - Forgetting to
returnthe result of the recursive call.sum_of_digits(n // 10)on its own line computes the value and throws it away. - Using a mutable default argument such as
memo={}and being surprised that it persists between calls. Here that persistence is exactly what you want, but know that it happens.
Practice: Sum of Digits (Recursive), Power with Fast Exponentiation, Fibonacci with Memoization
Binary trees
A binary tree is either empty (None) or a node with a value and two subtrees, left and right, each of which is itself a binary tree. Some vocabulary:
- the root is the topmost node; a leaf has no children;
- a node's children are its left and right; it is their parent; the subtree rooted at a node is that node plus everything below it;
- the depth of a node is the number of edges from the root to it; the height of a tree is the number of nodes (or edges, depending on the problem) on the longest root-to-leaf path.
On this site trees are made of TreeNode objects, which are always available:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
The level-order list format
Writing out nested TreeNode(...) calls is tedious, so tests describe trees as a level-order list, the convention the tree problems here use. Read the list top to bottom, left to right, one level at a time; None marks a missing child, and trailing Nones are dropped.
8
/ \
4 13
/ \
11 6
root = build_tree([8, 4, 13, None, None, 11, 6])
print(root.val, root.left.val, root.right.left.val)
print(tree_to_list(root))
8 4 11
[8, 4, 13, None, None, 11, 6]
The two Nones say that node 4 has no children, so the next values 11 and 6 belong to 13. Problems that return a tree wrap your result in tree_to_list(...) so the grader can compare plain lists.
Depth-first traversal
Because a tree is defined recursively, most tree functions have the same shape: handle None, then do something with the node and the results from left and right. What differs is the order in which you visit the node relative to its subtrees:
- pre-order: node, left, right (good for copying or printing a tree);
- in-order: left, node, right (for a BST this gives sorted order);
- post-order: left, right, node (good when the node's answer depends on its children, like height).
def preorder(node, out):
if node is None:
return
out.append(node.val)
preorder(node.left, out)
preorder(node.right, out)
def inorder(node, out):
if node is None:
return
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)
def postorder(node, out):
if node is None:
return
postorder(node.left, out)
postorder(node.right, out)
out.append(node.val)
root = build_tree([1, 2, 3, 4, 5])
for f in (preorder, inorder, postorder):
out = []
f(root, out)
print(f.__name__, out)
preorder [1, 2, 4, 5, 3]
inorder [4, 2, 5, 1, 3]
postorder [4, 5, 2, 3, 1]
Notice how the traversals pass an accumulator list down; the alternative is to return lists and concatenate them, which is shorter but copies more.
Here is a typical recursive tree function, comparing two trees for equality. Both the None handling and the "combine the two subtree answers" step are in it:
def same_tree(a, b):
if a is None or b is None:
return a is b # both None -> True, one None -> False
return (a.val == b.val
and same_tree(a.left, b.left)
and same_tree(a.right, b.right))
print(same_tree(build_tree([6, 2, 9]), build_tree([6, 2, 9])))
print(same_tree(build_tree([6, 2]), build_tree([6, None, 2])))
True
False
Some problems want a function to return one thing (say, the height of a subtree) while tracking another (the best path seen so far). The usual pattern is a nested helper plus a nonlocal variable, or an attribute on self if you are inside a class. Diameter of a binary tree and "maximum path sum" are both this shape.
Iterative DFS with a stack
Recursion uses the call stack; you can replace it with your own stack to avoid depth limits or to pause and resume a traversal. Pre-order is the easiest: push the right child before the left so the left is popped first.
def preorder_iter(root):
out = []
stack = [root] if root else []
while stack:
node = stack.pop()
out.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return out
print(preorder_iter(build_tree([1, 2, 3, 4, 5])))
[1, 2, 4, 5, 3]
Iterative in-order needs a little more care: walk as far left as you can, pushing nodes; pop one, visit it, then step to its right child and repeat.
def inorder_iter(root):
out, stack, node = [], [], root
while stack or node:
while node: # go as far left as possible
stack.append(node)
node = node.left
node = stack.pop() # the leftmost unvisited node
out.append(node.val)
node = node.right
return out
print(inorder_iter(build_tree([1, 2, 3, 4, 5])))
[4, 2, 5, 1, 3]
Being able to stop this loop early is what makes it useful: if you only need the k-th value, you can return the moment you have counted k pops.
Breadth-first traversal with a deque
DFS dives down one branch before looking at the next. Breadth-first search (BFS) visits all nodes at depth 0, then depth 1, and so on. It needs a queue, and collections.deque gives O(1) popleft:
from collections import deque
def bfs(root):
out = []
queue = deque([root]) if root else deque()
while queue:
node = queue.popleft()
out.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return out
print(bfs(build_tree([1, 2, 3, 4, 5])))
[1, 2, 3, 4, 5]
The output is simply the level-order list without the Nones. To group values by level, note that at the start of each round len(queue) is exactly the number of nodes on the current level: pop that many, collect them into one inner list, and everything you pushed in the meantime is the next level. BFS is also the right tool for "minimum depth" and "rightmost node on each level" questions, because it reaches shallow nodes before deep ones.
Common mistakes
- Forgetting that
Noneis a valid tree. Almost every helper needsif node is None:as its first line. - Treating
Noneas a leaf. A leaf is a node withleft is None and right is None; theNoneyou reach below a leaf is not itself a leaf, which matters for path-sum problems. - Returning
Nonefrom a function that should return the modified root. In-place transforms like inverting a tree must stillreturn root. - Using
list.pop(0)as a queue. It is O(n); usedeque.popleft().
Practice: Levels in an Org Chart, Mirror Image of a Tree, Hiking Route With an Exact Climb, Floor-by-Floor Roll Call, Widest Span of a Tree, Lowest Common Ancestor
Binary search trees
A binary search tree (BST) is a binary tree with an ordering invariant: for every node, every value in its left subtree is smaller than the node's value, and every value in its right subtree is larger. The word every is what people get wrong. It is not enough for the immediate children to be on the correct side; a grandchild in the right subtree must still be larger than the grandparent.
5
/ \
4 6
/ \
3 7 <- 3 is in 5's right subtree but 3 < 5: NOT a BST
The invariant buys you fast search. At each node you compare the target with the node's value and go left or right, discarding half the tree if it is balanced:
def search_bst(node, target):
while node is not None and node.val != target:
node = node.left if target < node.val else node.right
return node
def insert_bst(node, val):
if node is None:
return TreeNode(val)
if val < node.val:
node.left = insert_bst(node.left, val)
else:
node.right = insert_bst(node.right, val)
return node
root = None
for v in [5, 3, 8, 1, 4]:
root = insert_bst(root, v)
print(tree_to_list(root))
print(search_bst(root, 4).val)
print(search_bst(root, 7))
[5, 3, 8, 1, 4]
4
None
Insertion follows the same path a search would take and hangs the new node where the search fell off the tree. Note the recursive insert returns the (possibly new) subtree root and the caller stores it: node.left = insert_bst(node.left, val). That pattern of "return the new subtree" shows up in deletion and in tree-building problems too.
In-order gives sorted order
Because the left subtree is smaller and the right subtree is larger, an in-order traversal of a BST visits values in ascending order:
print(inorder_iter(root))
[1, 3, 4, 5, 8]
This single fact solves a family of problems. The k-th smallest value is the k-th node visited in-order. The tree is a valid BST if and only if the in-order sequence is strictly increasing. The in-order successor of a node is the next value in that sequence. Whenever a BST problem seems hard, ask what the in-order traversal looks like.
The other standard technique is to pass bounds down the tree: every value in the subtree under node.left must be less than node.val, and everything under node.right must be greater. A helper valid(node, low, high) that tightens one bound on each step visits every node once and never needs to build a list.
Common mistakes
- Validating only
node.left.val < node.val < node.right.val. The tree above passes that check and is still wrong. - Using
<=when the problem forbids duplicates (or vice versa). Read the constraints. - Initialising the bounds with
0or-1instead offloat('-inf')andfloat('inf'); node values can be negative.
Practice: Audit a Search Tree, k-th Lowest Bid in a Search Tree
Deleting a key
Searching and inserting are the easy half. Deletion has three cases, and only the third is interesting.
A node with no children is simply unhooked. A node with one child is replaced by that child, which is safe because every key in that child's subtree was already on the same side of the parent. A node with two children cannot be unhooked at all: both subtrees would come loose.
The repair is to leave the node where it is and give it a new key — the symmetric successor, the smallest key in its right subtree, reached by one step right and then left as far as possible. That key is the smallest one still larger than the node's, so putting it there keeps the search order intact. And the node it came from is easy to remove, because the leftmost node of a subtree has no left child and therefore falls into one of the first two cases.
class Node:
def __init__(self, v):
self.val = v
self.left = self.right = None
def insert(root, v):
if root is None:
return Node(v)
if v < root.val:
root.left = insert(root.left, v)
elif v > root.val:
root.right = insert(root.right, v)
return root
def remove(root, v):
if root is None:
return None
if v < root.val:
root.left = remove(root.left, v)
elif v > root.val:
root.right = remove(root.right, v)
else:
if root.left is None:
return root.right
if root.right is None:
return root.left
heir = root.right
while heir.left:
heir = heir.left
root.val = heir.val
root.right = remove(root.right, heir.val)
return root
def inorder(n):
return inorder(n.left) + [n.val] + inorder(n.right) if n else []
root = None
for v in [20, 10, 30, 5, 15, 25, 40]:
root = insert(root, v)
print(inorder(root))
root = remove(root, 20)
print(inorder(root), "new root:", root.val)
[5, 10, 15, 20, 25, 30, 40]
[5, 10, 15, 25, 30, 40] new root: 25
The symmetric predecessor — the largest key in the left subtree, one step left and then right as far as possible — works just as well and gives a different, equally valid tree. Always taking from the same side gradually shortens that subtree, so a long run of deletions skews the tree; implementations that care alternate between the two.
A clean way to write all of this is to let each call return the subtree that should hang where it was called, so the caller writes root.left = remove(root.left, value) and nobody has to keep track of parents.
The reason to care is what repeated use does to the shape. A search tree built from random keys has expected height \Theta(\log n), but a tree that is deleted from and inserted into over and over drifts towards \Theta(\sqrt{n}) — not a contrived worst case but ordinary wear. That is the argument for the next section.
Balanced trees and rotations
A search tree is only as fast as it is short. The fix is to measure the imbalance and repair it as soon as it appears.
Define the height of an empty tree as 0, so a leaf has height 1, and the balance factor of a node as the height of its left subtree minus the height of its right. A tree is an AVL tree when every node's balance factor is -1, 0 or 1.
That is a weak-sounding condition, but it is enough. The sparsest AVL tree of height h is a root over the sparsest trees of heights h-1 and h-2, so N(h) = 1 + N(h-1) + N(h-2), which is the Fibonacci recurrence:
def min_nodes(h):
a, b = 0, 1
for _ in range(max(0, h - 1)):
a, b = b, 1 + a + b
return b if h else 0
for h in range(1, 11):
print(h, min_nodes(h))
1 1
2 2
3 4
4 7
5 12
6 20
7 33
8 54
9 88
10 143
N(h) grows like \varphi^{h}, so a tree of n nodes has height at most about 1.44\log_2 n: a search is logarithmic, guaranteed, not just on average.
Rotations
The repair tool is the rotation, which re-hangs one subtree and changes nothing else — in particular an in-order walk reads the same keys in the same order before and after:
y x
/ \ / \
x C ==> A y
/ \ / \
A B B C
In code that is three assignments: pivot = y.left, y.left = pivot.right, pivot.right = y, and the pivot is the new root of the subtree. A left rotation is the mirror image.
Which rotation
When a node's balance factor reaches \pm 2, which rotation to apply is decided by the heavy child's own balance, not by the key that caused the trouble:
| the node leans | the heavy child leans | case | repair |
|---|---|---|---|
| left | left or level | LL | rotate the node right |
| left | right | LR | rotate the child left, then the node right |
| right | right or level | RR | rotate the node left |
| right | left | RL | rotate the child right, then the node left |
A straight line needs one rotation; a zig-zag has to be straightened first, which is what the double rotation does.
Keeping it balanced
Store the height on each node and refresh it the moment either child changes. Insertion is then the ordinary search-tree insertion with one extra line on the way out of the recursion: refresh the height, read the balance factor, and rotate if it has reached \pm 2. Because the recursion unwinds from the new leaf up to the root, every ancestor gets its chance, and for an insertion one rotation at the lowest unbalanced node is always enough.
Deletion is the same idea with one difference that catches people out: a deletion can unbalance several ancestors, so the rebalancing must continue all the way to the root rather than stopping at the first repair. The other difference is that the heavy child can have balance 0, which insertion never produces; that is the single-rotation case.
Red-black trees make a weaker promise (height at most 2\log_2(n+1)) and rebalance a little less often, which is why most standard libraries use them for their ordered maps. The idea is the same: a bound on the height, maintained by rotations.
Heaps with heapq
A heap is a tree stored in a flat list, arranged so that the smallest element is always at index 0. Pushing or popping costs O(log n) and peeking at the minimum costs O(1). You never need to build one by hand: the heapq module (already imported on this site) operates on ordinary lists.
import heapq
h = []
for x in [5, 1, 8, 3]:
heapq.heappush(h, x)
print(h[0])
print(heapq.heappop(h))
print(heapq.heappop(h))
nums = [9, 4, 7]
heapq.heapify(nums) # turn an existing list into a heap in O(n)
print(nums[0])
1
1
3
4
Remember that only h[0] is meaningful; the rest of the list is in "heap order", not sorted order, so never read h[-1] expecting the maximum.
Max-heap by negation
heapq only provides a min-heap. To get the largest element first, push the negated value and negate it again on the way out:
h = []
for x in [5, 1, 8]:
heapq.heappush(h, -x)
print(-heapq.heappop(h))
8
Tuples as heap items
When you need to order objects by some key, push tuples. Tuples compare element by element, so the first element is the priority and later elements break ties:
tasks = []
heapq.heappush(tasks, (2, "write tests"))
heapq.heappush(tasks, (1, "fix bug"))
heapq.heappush(tasks, (2, "refactor"))
print(heapq.heappop(tasks))
print(heapq.heappop(tasks))
(1, 'fix bug')
(2, 'refactor')
There is a trap here. If two tuples tie on every element up to an object that does not support <, such as a ListNode, Python raises TypeError. The standard fix is to include a unique integer (an index or a counter) before the object: (node.val, i, node). The index settles ties, so the node itself is never compared.
The bounded heap pattern
Most "k largest / k smallest / k closest / k most frequent" problems use one idea: keep a heap of size at most k and evict whenever it grows to k + 1. To keep the k largest values, use a min-heap, because the element you want to evict is the smallest of the ones kept:
def k_largest(nums, k):
h = []
for x in nums:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h) # drop the smallest of the k+1
return sorted(h, reverse=True)
print(k_largest([7, 15, 2, 9, 4, 13, 1], 3))
[15, 13, 9]
After the loop, h[0] is the k-th largest element overall. Symmetrically, to keep the k smallest (or closest) you evict the largest, so you need a max-heap: push the negated key. This runs in O(n log k), which beats sorting when k is much smaller than n, and works on a stream where you never see all the data at once.
For one-off use, heapq.nlargest(k, items, key=...) and heapq.nsmallest implement this pattern for you:
print(heapq.nlargest(2, ["aa", "b", "ccc"], key=len))
['ccc', 'aa']
K-way merge
The last heap pattern merges k sorted sequences. Put the first element of every sequence in a heap, tagged with which sequence it came from. Repeatedly pop the smallest, emit it, and push the next element from the same sequence. Each element enters and leaves the heap once, so merging N elements across k lists costs O(N log k). With linked lists the "next element" is just node.next, and you stitch popped nodes together with a dummy head and a tail pointer, exactly as you did when merging two lists in Phase 2.
Common mistakes
- Forgetting that
heapqis a min-heap and popping the wrong end of the problem. - Reading
h[-1]or iterating overhexpecting sorted order. - Pushing bare objects that cannot be compared, then hitting
TypeErroron the first tie. - Calling
sorted()inside a loop that runs n times: the point of a heap is to avoid that O(n^2 log n) cost.
Practice: Live Qualifying Cut-off, Most-Requested Songs, Nearest Charging Stations, Merging k Sorted Sensor Logs
Heapsort: sorting with the array you already have
heapq hides the array, but a binary heap is an array, filled level by level from the left. With 0-based indices the node at i has children at 2*i + 1 and 2*i + 2 and parent at (i - 1) // 2. No node objects, no pointers: the tree structure is arithmetic, and the children of a node sit next to each other in memory.
Two operations maintain it. Sift-up carries a newly appended item towards the root while it beats its parent. Sift-down sinks an item that is too small, always swapping with the larger of its two children — swapping with the smaller one would leave that child below its sibling and break the property again.
Building a heap from an arbitrary array does not need n insertions. The second half of the array is all leaves, and a leaf is already a heap of one, so it is enough to sift down the nodes from \lfloor n/2 \rfloor - 1 back to 0, each into subtrees that are already heaps. That costs \Theta(n), not \Theta(n\log n): half the nodes never move, a quarter move at most one level, an eighth at most two, and the series converges.
Once the array is a max-heap, sorting it needs no extra memory at all. Swap the root, which holds the largest value, with the last item of the heap; the heap is now one shorter and that item is in its final place; sift the new root down within what remains. Repeat.
def sink(a, i, size):
while True:
big = i
l, r = 2 * i + 1, 2 * i + 2
if l < size and a[l] > a[big]:
big = l
if r < size and a[r] > a[big]:
big = r
if big == i:
return
a[i], a[big] = a[big], a[i]
i = big
def heapsort(a):
n = len(a)
for i in range(n // 2 - 1, -1, -1):
sink(a, i, n)
print("after build:", a)
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
sink(a, 0, end)
return a
print("sorted: ", heapsort([4, 10, 3, 5, 1]))
after build: [10, 5, 3, 4, 1]
sorted: [1, 3, 4, 5, 10]
Heapsort is the sort that is \Theta(n\log n) in the worst case and uses \Theta(1) extra memory — merge sort gives up the memory, quicksort gives up the worst case. What it gives up instead is locality: each sift-down jumps about the array, so in practice a well-implemented quicksort usually wins on speed despite the worse guarantee.
| operation | search tree (balanced) | heap |
|---|---|---|
| insert | \Theta(\log n) | \Theta(\log n) |
| find a given key | \Theta(\log n) | \Theta(n) |
| minimum or maximum | \Theta(\log n) | \Theta(1) for the end it is built for |
| delete the extreme | \Theta(\log n) | \Theta(\log n) |
| build from n items | \Theta(n\log n) | \Theta(n) |
A heap is not a search tree with a different rule: it knows only which item is extreme, and finding any other key means scanning the whole array.
Online problems and caching
An online algorithm must make each decision as the input arrives, without seeing the future. A cache is the standard example: it holds k pages, requests arrive one at a time, a request for a page that is not in the cache is a miss, and on a miss with a full cache you must choose a page to evict. LRU (least recently used) evicts the page untouched for longest; an OrderedDict does it in O(1) per request:
from collections import OrderedDict
def lru_misses(requests, capacity):
cache, misses = OrderedDict(), 0
for page in requests:
if page in cache:
cache.move_to_end(page) # now the most recently used
else:
misses += 1
if len(cache) == capacity:
cache.popitem(last=False) # evict the least recently used
cache[page] = True
return misses
print(lru_misses([1, 2, 3, 1, 4, 1, 2, 5, 1, 2, 3, 4], 3))
8
If you could see the future (an offline algorithm), the best rule is known: evict the page whose next use is furthest away (Belady's rule). A max-heap of "next use" positions finds that page quickly; stale heap entries are skipped, exactly as in Dijkstra:
import heapq
def optimal_misses(requests, capacity):
# Belady: on a miss with a full cache, evict the page used again furthest in the future
INF = float("inf")
nxt, last = [INF] * len(requests), {}
for i in range(len(requests) - 1, -1, -1):
nxt[i] = last.get(requests[i], INF)
last[requests[i]] = i
cache, heap, misses = {}, [], 0 # heap of (-next use, page); stale entries skipped
for i, page in enumerate(requests):
if page not in cache:
misses += 1
if len(cache) == capacity:
while True:
neg, victim = heapq.heappop(heap)
if cache.get(victim) == -neg:
break
del cache[victim]
cache[page] = nxt[i]
heapq.heappush(heap, (-nxt[i], page))
return misses
print(optimal_misses([1, 2, 3, 1, 4, 1, 2, 5, 1, 2, 3, 4], 3))
7
Comparing the two tells you how much not knowing the future costs. The worst-case ratio between an online algorithm and the best offline one is its competitive ratio; for LRU with a cache of size k it is k, and no deterministic online rule does better.
Common mistakes: forgetting to refresh a page on a hit (move_to_end), which turns LRU into FIFO. Counting the first k distinct pages as hits. In the offline rule, treating "never used again" as position 0 instead of infinity.
Practice: The Reading-Room Shelf, Reels in the Projection Booth, Rent or Buy the Snowboard
Hash tables from the inside
A Python dict answers "is this key here?" in constant time, and the previous phase used that without asking how. The answer is worth knowing, because every part of it can go wrong.
A lookup happens in two steps. Pre-hashing turns the key into a non-negative integer; for a string that is usually a polynomial in the character codes, evaluated with Horner's rule so the running value never grows:
def prehash(word, base=31, width=64):
mask = (1 << width) - 1
value = 0
for ch in reversed(word):
value = (value * base + ord(ch)) & mask
return value
Then a hash function squeezes that integer into a slot index. Two classics:
- division:
h(k) = k % m. Simple, but it inherits any pattern the keys have. Ifmis a power of two it keeps only the low bits; if the keys are all multiples ofm, every one of them lands in slot 0. - multiplication:
h(k) = ((a * k) % 2**w) >> (w - r)for a table of m = 2^{r} slots. Multiplying by a constant mixes the high bits of the key down into the low ones, and the toprbits of the product are then taken.
from collections import Counter
keys = [i * 8 for i in range(32)]
m = 8
print("division ", sorted(Counter(k % m for k in keys).values(), reverse=True))
A = 2654435769
print("multiply ", sorted(Counter(((A * k) & 0xFFFFFFFF) >> 29 for k in keys).values(), reverse=True))
division [32]
multiply [6, 5, 4, 4, 4, 4, 3, 2]
Thirty-two keys, all multiples of 8, into eight slots: the division method puts every one of them in the same bucket while the multiplication method spreads them. Measure a hash function by its fullest bucket, because that is what a lookup costs in the worst case, not by its average.
Two ways to live with collisions
Separate chaining keeps a list per slot. An insert searches its own list first, so a key is stored once; a lookup walks one list. The table never fills up, and the cost is the length of the longest chain.
Open addressing stores everything in the array itself. A key probes a sequence of slots until it finds an empty one:
- linear probing: s(k, j) = (k + j) \bmod m — cache-friendly, but keys clump into long runs;
- quadratic probing: s(k, j) = (k + c_1 j + c_2 j^{2}) \bmod m — breaks up the runs;
- double hashing: s(k, j) = (h(k) + j \cdot h'(k)) \bmod m — the step size depends on the key, so two keys that start in the same slot do not follow the same path.
The step and the table size must be coprime, or the probe sequence cycles through only part of the table and can fail while the table is half empty.
The hole that swallows the key behind it
Deletion is where open addressing goes wrong. Emptying a slot cuts the probe sequence of every key that was stored behind it during insertion, and those keys silently become unreachable. The fix is a tombstone: a third slot state meaning "something used to live here, keep walking", which a later insertion may overwrite.
EMPTY, GONE = "-", "x"
slots = [EMPTY] * 3
def put(key):
i = key % 3
while slots[i] not in (EMPTY, GONE):
i = (i + 1) % 3
slots[i] = key
def find(key):
i = key % 3
for _ in range(3):
if slots[i] is EMPTY:
return False
if slots[i] == key:
return True
i = (i + 1) % 3
return False
put(1); put(4)
print(slots)
slots[1] = EMPTY # the wrong way to delete 1
print("after blanking: find(4) =", find(4))
slots[1] = GONE # a tombstone instead
print("after tombstone: find(4) =", find(4))
['-', 1, 4]
after blanking: find(4) = False
after tombstone: find(4) = True
The load factor
Everything above stays fast only while the table has room. The load factor is the number of stored keys divided by the number of slots, and when it passes a threshold — a half for open addressing, around one for chaining — the table doubles and every key is rehashed into the new array. A resize costs \Theta(m), but the next one cannot come until the stored count has doubled again, so spread over the insertions it adds a constant: insertion is \Theta(1) amortised.
Tries
A trie (from retrieval, usually pronounced "try") stores strings so that words with a common prefix share a common path. Each node has one child per possible next character. In Python the simplest representation is a dictionary of dictionaries: the keys are characters and the values are child nodes.
trie = {}
for word in ["car", "cat"]:
node = trie
for ch in word:
node = node.setdefault(ch, {}) # create the child if missing, then step into it
node["$"] = True # mark that a word ends here
print(trie)
{'c': {'a': {'r': {'$': True}, 't': {'$': True}}}}
The "$" marker distinguishes a stored word from a mere prefix: "ca" is on the path to both words, but it is not a word itself, so its node has no "$". Looking something up is the same walk without the setdefault: step through the characters, and if a character is ever missing, the string is not in the trie. Whether you then require the "$" marker at the end is the only difference between "is this a whole word?" and "is this a prefix of some word?".
Why bother, when a Python set already answers "is this word stored?" in O(1)? Because a set cannot answer prefix questions without scanning every entry. A trie answers "does any word start with pre?" in O(3) steps, and can then list all completions by walking the subtree below. That makes tries the structure behind autocomplete, spell-checking, and longest-prefix matching in routers. Word-search puzzles on a grid (Phase 5) also use a trie to prune dead-end paths early.
Common mistakes
- Using the same character as an end marker that could appear in a word.
"$"or"#"is safe for lowercase words; for arbitrary strings use a separate boolean attribute on a smallTrieNodeclass instead. - Returning
Truefromsearchas soon as the walk succeeds, which makessearchbehave likestarts_with. - Forgetting that
insertmust step into the newly created child (node = node.setdefault(...)), not just create it.
Practice: A Prefix Tree for Autocomplete
Checklist
Before moving on to Phase 5, make sure you can:
- Write a recursive function by naming its base case and recursive case, and trace it on paper.
- Explain why deep recursion raises
RecursionErrorand rewrite a recursion with an explicit stack or a loop. - Halve the problem size per step (as in fast exponentiation) and recognise when that is possible.
- Spot overlapping subproblems and add memoization with a dictionary or
lru_cache. - Read and write the level-order list format and use
build_tree/tree_to_list. - Write pre-order, in-order and post-order traversals, both recursively and with an explicit stack.
- Write a BFS with
dequeand group the output by level. - Write the standard tree recursion: handle
None, recurse on both children, combine. - Track a "best so far" value across a recursion with
nonlocal. - State the BST invariant precisely and validate it with bounds or an in-order check.
- Search and insert in a BST, and use in-order traversal to get sorted order.
- Use
heapq.heappush,heappop,heapify,nlargest; simulate a max-heap by negation. - Apply the bounded heap of size k pattern and the k-way merge pattern.
- Push tuples with a tie-breaking index so incomparable objects are never compared.
- Build a trie from nested dictionaries with an end-of-word marker, and tell
searchfromstarts_with. - Count the misses of an LRU cache with an
OrderedDict, and of the optimal offline rule (evict the page used furthest in the future) with a heap.