Exercises
Fifteen problems covering the whole course: elementary structures, hashing, search trees, red-black trees, augmented trees, B-trees and disjoint sets. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: For tree problems, draw the tree after every step, with colours or sizes written next to the keys. For hashing problems, write the table as a row of slots and fill it in pencil. Nearly every mistake in this course's material is a pointer or an index updated in the wrong order, and a drawing exposes it.
| # | Exercise | Practises |
|---|---|---|
| 1 | Growth by any factor | dynamic arrays |
| 2 | A stack that knows its minimum | stacks, invariants |
| 3 | A double-ended circular buffer | queues |
| 4 | How many slots stay empty? | chaining, indicator variables |
| 5 | Dropping the | universal hashing |
| 6 | Linear probing by hand | open addressing, clustering |
| 7 | Probes at 80 percent | open-addressing analysis |
| 8 | Orders that build the same tree | BST insertion |
| 9 | Successor without parent pointers | BST queries |
| 10 | Red-black insertion of sorted keys | red-black insertion |
| 11 | Only children in a red-black tree | red-black properties |
| 12 | The -th successor | order-statistic trees |
| 13 | Every overlapping interval | interval trees |
| 14 | Extremes of a B-tree | B-tree height |
| 15 | Union-find by hand | union by rank, path compression |
Exercise 1: Growth by any factor
A dynamic array starts with capacity 1 and multiplies its capacity by whenever it is full (rounding up). Bound the number of element copies made during appends.
Answer
Fewer than copies: for doubling, for , for .
Solution
Ignoring rounding, the capacities are where is the last capacity that filled up, so . Each resize copies the full old capacity, so the copies number
A smaller factor wastes less memory but copies more: the trade-off from Dynamic Arrays and Doubling. Rounding up only makes capacities larger and resizes rarer.
Exercise 2: A stack that knows its minimum
Design a stack that supports PUSH, POP and MIN (return the smallest element currently on the stack), each in worst-case time.
Answer
Keep a second stack of minima: on PUSH push onto it, and pop it together with the main stack. MIN reads its top.
Solution
Invariant: the -th entry of the minima stack is the minimum of the first entries of the main stack. PUSH extends both stacks and keeps it, because the minimum of entries is the smaller of the new entry and the minimum of the first . POP removes the top of both, which leaves the first entries, whose minimum is the new top. Each operation is . The space doubles in the worst case; storing a minimum only when it changes (with a count) saves space when many pushes are larger than the minimum.
class MinStack:
def __init__(self):
self.items, self.mins = [], []
def push(self, x):
self.items.append(x)
self.mins.append(x if not self.mins else min(x, self.mins[-1]))
def pop(self):
self.mins.pop()
return self.items.pop()
def min(self):
return self.mins[-1]
s = MinStack()
for x in [5, 7, 3, 8, 3, 1]:
s.push(x)
print(f"push {x}: min {s.min()}")
while s.items:
x = s.pop()
print(f"pop {x}: min {s.min() if s.items else '-'}")push 5: min 5
push 7: min 5
push 3: min 3
push 8: min 3
push 3: min 3
push 1: min 1
pop 1: min 3
pop 3: min 3
pop 8: min 3
pop 3: min 5
pop 7: min 5
pop 5: min -
Exercise 3: A double-ended circular buffer
Extend the circular-buffer queue of Queues and Circular Buffers (fields head and size in an array of slots) to a deque: insert and delete at both ends in . Give the index formulas.
Answer
PUSH-BACK writes slot ; POP-BACK reads slot ; PUSH-FRONT sets and writes there; POP-FRONT reads and sets . Each adjusts size by one.
Solution
The invariant is unchanged: the elements, front to back, are in slots for . Adding at the back uses the slot after the last element; adding at the front moves head one slot back, wrapping from 0 to (in Python (head - 1) % m does this, in C++ write (head + m - 1) % m, because % of a negative number is negative there). Removing at the back only decreases size. All four operations are in the worst case; overflow and underflow checks are as for the queue. collections.deque and std::deque offer the same interface with blocks instead of one ring.
Exercise 4: How many slots stay empty?
Under simple uniform hashing, keys are stored in a chained table of slots. What is the expected number of empty slots? Evaluate it for .
Answer
; for about 367.7, a little over a third of the table.
Solution
Let indicate that slot is empty. Each key misses slot with probability , independently, so , and by linearity the expected number of empty slots is . Since , this is about . The simulation below agrees, and it matches the Poisson shape seen in Hash Tables with Chaining.
import math, random
m = n = 1000
rng = random.Random(6)
trials = 200
empty = 0
for _ in range(trials):
used = {rng.randrange(m) for _ in range(n)}
empty += m - len(used)
print(f"exact {m * (1 - 1 / m) ** n:.1f}, approximation m e^-alpha = {m * math.exp(-n / m):.1f}, simulated {empty / trials:.1f}")exact 367.7, approximation m e^-alpha = 367.9, simulated 368.8
Exercise 5: Dropping the
Is the family for (that is, universal hashing's with ) universal? Test it for , .
Answer
No. For and there are 16 functions, so universality allows at most of them to make a pair collide, but some pairs collide under 4.
Solution
Without , step 2 of the universality proof fails: a pair of residues now determines , but not every pair with is reached, since there are only functions for pairs. The images and are tied together (), and for some pairs of keys that relation favours collisions modulo . The program finds the worst pairs.
from itertools import combinations
p, m = 17, 5
family = range(1, p)
def collisions(k, l):
return sum(((a * k) % p) % m == ((a * l) % p) % m for a in family)
worst = max(collisions(k, l) for k, l in combinations(range(p), 2))
pairs = [(k, l) for k, l in combinations(range(p), 2) if collisions(k, l) == worst]
print(f"{len(family)} functions, bound |H|/m = {len(family) / m}; worst pairs collide under {worst} functions")
print("for example", pairs[:4])16 functions, bound |H|/m = 3.2; worst pairs collide under 4 functions
for example [(1, 3), (1, 6), (1, 10), (1, 11)]
The family is still "almost universal" (collision probability at most about ), which is good enough for many uses, but the clean needs the .
Exercise 6: Linear probing by hand
Insert the keys 27, 40, 5, 16, 49, 38, 60, 3, in that order, into a table of slots with linear probing and . Give the final table and the number of probes of each insertion.
Answer
Slots 0 to 10: 60, -, -, 3, -, 27, 5, 40, 16, 49, 38. Probes: 1, 1, 2, 4, 5, 6, 7, 1.
Solution
Six of the keys (27, 5, 16, 49, 38, 60) hash to slot 5, and 40 to slot 7, inside their run. Each new key with hash 5 walks to the end of the growing run: 5 lands in 6, 16 skips 5 to 7 and lands in 8, 49 in 9, 38 in 10, and 60 wraps around to slot 0 after seven probes. 3 hashes to the empty slot 3. That is primary clustering at its worst (Open Addressing); the practice problem Linear Probing Table asks for exactly this computation.
m, table = 11, [None] * 11
for k in [27, 40, 5, 16, 49, 38, 60, 3]:
j, probes = k % m, 1
while table[j] is not None:
j, probes = (j + 1) % m, probes + 1
table[j] = k
print(f"insert {k}: home slot {k % m}, stored in slot {j} after {probes} probe(s)")
print(["-" if v is None else v for v in table])insert 27: home slot 5, stored in slot 5 after 1 probe(s)
insert 40: home slot 7, stored in slot 7 after 1 probe(s)
insert 5: home slot 5, stored in slot 6 after 2 probe(s)
insert 16: home slot 5, stored in slot 8 after 4 probe(s)
insert 49: home slot 5, stored in slot 9 after 5 probe(s)
insert 38: home slot 5, stored in slot 10 after 6 probe(s)
insert 60: home slot 5, stored in slot 0 after 7 probe(s)
insert 3: home slot 3, stored in slot 3 after 1 probe(s)
[60, '-', '-', 3, '-', 27, 5, 40, 16, 49, 38]
Exercise 7: Probes at 80 percent
An open-addressing table is 80 percent full. Using the bounds for uniform hashing and Knuth's approximations for linear probing, how many probes do an unsuccessful and a successful search make on average?
Answer
Uniform hashing: at most 5 (unsuccessful) and about 2.01 (successful). Linear probing: about 13 and 3.
Solution
With : , and . Knuth's formulas for linear probing give and . Clustering costs linear probing more than double for unsuccessful searches at this load. See Analysis of Open Addressing.
Exercise 8: Orders that build the same tree
How many of the insertion orders of the keys 1 to 7 produce the perfectly balanced BST with root 4?
Answer
Solution
An insertion order builds a given tree exactly when every node comes before all the other nodes of its subtree. Count recursively: 4 must come first; the remaining six keys split into and , which can be interleaved in ways, and each side must itself build its subtree: 2 first, then 1 and 3 in either order, so 2 ways per side. Total . In general the count is divided by the product of all subtree sizes: .
from itertools import permutations
def shape(order):
root = None
for k in order:
if root is None:
root = [k, None, None]; continue
x = root
while True:
i = 1 if k < x[0] else 2
if x[i] is None:
x[i] = [k, None, None]; break
x = x[i]
return repr(root)
target = shape([4, 2, 6, 1, 3, 5, 7])
print(sum(shape(p) == target for p in permutations(range(1, 8))), "of 5040 orders build the balanced tree")80 of 5040 orders build the balanced tree
Exercise 9: Successor without parent pointers
Your BST nodes have no parent field. Give an procedure for the successor of key (which is in the tree).
Answer
Search for from the root, remembering the last node at which the search went left. If 's node has a right subtree, the successor is that subtree's minimum; otherwise it is the remembered node (or none).
Solution
Case 2 of Successor and Predecessor climbs to the lowest ancestor whose left subtree contains . Those ancestors are exactly the nodes where the search for turned left, and the lowest one is the last such turn. So one downward search records the candidate, and case 1 needs no parent at all. Both parts follow one path: . The same trick computes a ceiling ( key ) for any , even if is not stored.
Exercise 10: Red-black insertion of sorted keys
Insert the keys 1, 2, …, 15 in increasing order into an empty red-black tree. What are the height and the black-height of the result, and where are the red nodes?
Answer
Height 5, black-height 3. The red nodes are 8, 12, 13 and 15: all on or next to the right edge of the tree.
Solution
Each insertion goes to the far right, so the fix-ups always happen on the right spine: a red-red pair there is repaired by a case-3 left rotation when the uncle is black, or pushed up by a case-1 recolouring when it is red. The left part of the tree ends up perfectly balanced and all black, the right part has alternating colours. The height 5 is well below , but above the 3 of a perfect tree. The program uses the insertion of Red-Black Insertion.
RED, BLACK = "R", "B"
class Node:
__slots__ = ("key", "color", "left", "right", "parent")
def __init__(self, key, color, nil):
self.key, self.color, self.left, self.right, self.parent = key, color, nil, nil, nil
class RBTree:
def __init__(self):
self.nil = Node(None, BLACK, None)
self.root = self.nil
def rotate(self, x, d):
nil, o = self.nil, ("right" if d == "left" else "left")
y = getattr(x, o)
setattr(x, o, getattr(y, d))
if getattr(y, d) is not nil: getattr(y, d).parent = x
y.parent = x.parent
if x.parent is nil: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
setattr(y, d, x)
x.parent = y
def insert(self, key):
z, y, x = Node(key, RED, self.nil), self.nil, self.root
while x is not self.nil:
y, x = x, (x.left if key < x.key else x.right)
z.parent = y
if y is self.nil: self.root = z
elif key < y.key: y.left = z
else: y.right = z
while z.parent.color == RED:
p = z.parent; g = p.parent
a, b = ("left", "right") if p is g.left else ("right", "left")
u = getattr(g, b)
if u.color == RED:
p.color = u.color = BLACK; g.color = RED; z = g; continue
if z is getattr(p, b):
z = p; self.rotate(z, a); p = z.parent
p.color = BLACK; g.color = RED; self.rotate(g, b)
self.root.color = BLACK
def show(t, x):
if x is t.nil: return "-"
s = f"{x.key}{x.color}"
return s if x.left is t.nil and x.right is t.nil else f"{s}({show(t, x.left)}, {show(t, x.right)})"
def height(t, x):
return -1 if x is t.nil else 1 + max(height(t, x.left), height(t, x.right))
def black_height(t):
x, b = t.root, 0
while x is not t.nil:
x = x.left
b += x.color == BLACK # count the blacks below the root, NIL included
return b
t = RBTree()
for k in range(1, 16):
t.insert(k)
print(show(t, t.root))
print("height", height(t, t.root), "| black-height", black_height(t))4B(2B(1B, 3B), 8R(6B(5B, 7B), 10B(9B, 12R(11B, 14B(13R, 15R)))))
height 5 | black-height 3
Exercise 11: Only children in a red-black tree
In a red-black tree, a node has exactly one internal child (the other child is NIL). What can you say about ?
Answer
is red, and both of 's children are NIL. In particular is black.
Solution
The path from down its NIL side meets one black node (the NIL itself). By property 5, every path from through must also meet exactly one black node, and it ends in a black NIL, so must be red and every path from must reach a NIL with no black node in between: 's children are NIL leaves. Since is red, property 4 makes black. This is why the deletion procedure of Red-Black Deletion never has to handle a black node with a single internal child.
Exercise 12: The -th successor
In an order-statistic tree, give an procedure for the -th successor of node : the node whose rank is larger.
Answer
OS-SELECT, if that rank is at most .
Solution
OS-RANK costs one walk up and OS-SELECT one walk down, each, independent of . Calling TREE-SUCCESSOR times would cost , which is worse for large . A single-pass version is possible too: climb from while the target lies outside the current subtree, then descend with OS-SELECT inside it.
Exercise 13: Every overlapping interval
Modify INTERVAL-SEARCH of Interval Trees to report all stored intervals that overlap a query .
Answer
Recurse: at node , report if it overlaps; visit the left subtree if x.left.max >= i.low; visit the right subtree if x.low <= i.high. The cost is for reported intervals.
Solution
A subtree can contain an overlap only if its max is at least , which justifies the left test; every interval in the right subtree starts at or after , so if none of them overlaps , which justifies the right test. Every visited subtree that is not pruned contains at least one overlap on its own path, so each reported interval accounts for visited nodes. The program checks the procedure on random data with a simple BST augmented with max (the bound needs a balanced tree, the correctness does not).
import random
class Node:
__slots__ = ("low", "high", "max", "left", "right")
def __init__(self, low, high):
self.low, self.high, self.max, self.left, self.right = low, high, high, None, None
def insert(x, low, high):
if x is None: return Node(low, high)
if low < x.low: x.left = insert(x.left, low, high)
else: x.right = insert(x.right, low, high)
x.max = max(x.max, high)
return x
def all_overlaps(x, lo, hi, out):
if x is None: return out
if x.low <= hi and lo <= x.high: out.append((x.low, x.high))
if x.left is not None and x.left.max >= lo: all_overlaps(x.left, lo, hi, out)
if x.low <= hi: all_overlaps(x.right, lo, hi, out)
return out
rng = random.Random(12)
ivs = []
root = None
for _ in range(300):
a = rng.randrange(1000); b = a + rng.randrange(40)
root = insert(root, a, b); ivs.append((a, b))
for _ in range(500):
lo = rng.randrange(1000); hi = lo + rng.randrange(30)
assert sorted(all_overlaps(root, lo, hi, [])) == sorted(iv for iv in ivs if iv[0] <= hi and lo <= iv[1])
print("500 queries: all_overlaps reports exactly the overlapping intervals")
found = sorted(all_overlaps(root, 500, 510, []))
print(len(found), "stored intervals overlap [500, 510], for example", found[:3])500 queries: all_overlaps reports exactly the overlapping intervals
14 stored intervals overlap [500, 510], for example [(471, 500), (475, 510), (478, 500)]
Exercise 14: Extremes of a B-tree
A B-tree has minimum degree and height 2. What are the smallest and the largest number of keys it can hold? How many keys does a tree of height 3 need at least?
Answer
Height 2: at least and at most keys. Height 3: at least keys.
Solution
The fewest keys: a root with one key and two children, every other node with keys and children, so for height 2. The most: every node with keys and children; levels 0, 1, 2 hold nodes, so keys. These are the two extremes computed in B-Trees: Definition, Height and Search. So almost two million keys can live in a tree of height 2, and a height-3 tree is only forced once there are about two million.
Exercise 15: Union-find by hand
Elements 0 to 7 start as singletons. Apply, with union by rank (on equal ranks the first argument's root becomes the parent) and path compression: UNION(0, 1), UNION(2, 3), UNION(4, 5), UNION(6, 7), UNION(1, 3), UNION(5, 7), UNION(3, 7), FIND-SET(7). Give the parent array after each of the last two operations, and the final ranks.
Answer
After UNION(3, 7): parents [0, 0, 0, 0, 0, 4, 4, 4]. After FIND-SET(7): parents [0, 0, 0, 0, 0, 4, 4, 0]. Ranks: 0 has rank 3, 4 rank 2, 2 and 6 rank 1, the rest 0.
Solution
The first four unions make the pairs , , , with roots 0, 2, 4, 6 of rank 1. UNION(1, 3) finds roots 0 and 2 with equal ranks and links 2 under 0, which gets rank 2; UNION(5, 7) likewise links 6 under 4. In UNION(3, 7), FIND-SET(3) walks 3, 2, 0 and re-points 3 at the root 0; FIND-SET(7) walks 7, 6, 4 and re-points 7 at 4. The roots 0 and 4 both have rank 2, so 4 goes under 0, which gets rank 3. Finally FIND-SET(7) walks 7, 4, 0 and re-points 7 at 0. The ranks of 2, 4 and 6 stay as they were when they stopped being roots, and 0's rank 3 overstates the height of its tree (2 after the compressions), as ranks may.
p, rank = list(range(8)), [0] * 8
def find(x):
if p[x] != x:
p[x] = find(p[x]) # path compression
return p[x]
def union(x, y):
a, b = find(x), find(y)
if a == b: return
if rank[a] < rank[b]: a, b = b, a
p[b] = a
if rank[a] == rank[b]: rank[a] += 1
sets = 8
for x, y in [(0, 1), (2, 3), (4, 5), (6, 7), (1, 3), (5, 7), (3, 7)]:
sets -= find(x) != find(y)
union(x, y)
print(f"UNION({x}, {y}): parents {p}, {sets} set(s)")
find(7)
print("after FIND-SET(7): parents", p, "| ranks", rank)UNION(0, 1): parents [0, 0, 2, 3, 4, 5, 6, 7], 7 set(s)
UNION(2, 3): parents [0, 0, 2, 2, 4, 5, 6, 7], 6 set(s)
UNION(4, 5): parents [0, 0, 2, 2, 4, 4, 6, 7], 5 set(s)
UNION(6, 7): parents [0, 0, 2, 2, 4, 4, 6, 6], 4 set(s)
UNION(1, 3): parents [0, 0, 0, 2, 4, 4, 6, 6], 3 set(s)
UNION(5, 7): parents [0, 0, 0, 2, 4, 4, 4, 6], 2 set(s)
UNION(3, 7): parents [0, 0, 0, 0, 0, 4, 4, 4], 1 set(s)
after FIND-SET(7): parents [0, 0, 0, 0, 0, 4, 4, 0] | ranks [3, 0, 1, 0, 2, 0, 1, 0]
Counting the sets after each union, as the program does, is the practice problem Components After Each Union in miniature. See Forests: Union by Rank and Path Compression for the procedures.
Test yourself
Which structure answers "how many stored keys are smaller than ?" in time while also supporting insertions and deletions in ?
- a hash table with chaining
- a sorted dynamic array
- an order-statistic tree
- a disjoint-set forest
An open-addressing table with linear probing is 90 percent full. Roughly how many probes does an unsuccessful search make, by Knuth's approximation?
- 2
- 10
- 50
- 100
Which of these operations can make the height of a structure decrease?
- recolouring a node of a red-black tree
- a B-tree merge that empties the root
- a union in a disjoint-set forest
- inserting a key into a B-tree