Exercises
Fifteen problems covering the whole course: integer structures on the word-RAM, dynamic trees and connectivity, persistence and retroactivity, memory hierarchies, and succinct and probabilistic structures. Each has a short Answer and a full Solution; several solutions include a program you can edit and run. State every bound with its conditions (worst case, amortized, expected, model), as the lessons do.
Tip: Most problems here are about why a bound holds. Before calculating, ask which single step of the structure is expensive, and what pays for it: a halving of the universe, a potential, an amortization over operations, or the block size .
| # | Exercise | Practises |
|---|---|---|
| 1 | Two recursive calls | van Emde Boas recurrences |
| 2 | Lookups in an x-fast trie | binary search on prefixes |
| 3 | The wrong bucket size | y-fast tries, indirection |
| 4 | Sketch four keys | fusion nodes |
| 5 | Tours after LINK and CUT | Euler-tour trees |
| 6 | Lowest common ancestors with ACCESS | link-cut trees |
| 7 | How high can an edge climb? | dynamic connectivity levels |
| 8 | Paths in a persistent tree | path copying |
| 9 | A retroactive register | retroactivity |
| 10 | Passes of an external sort | DAM sorting bound |
| 11 | Searching a billion keys | B-trees, vEB layout |
| 12 | Rank and select by hand | rank/select |
| 13 | Merging Bloom filters | Bloom filters |
| 14 | Cuckoo graph cycles | cuckoo hashing |
| 15 | Backward search by hand | FM-index |
Exercise 1: Two recursive calls
A careless van Emde Boas implementation stores the minimum of each structure also inside its cluster (it does not keep it out of the recursion). Show that INSERT can then make two non-trivial recursive calls, and solve the resulting recurrence.
Answer
, which is : no better than a balanced BST.
Solution
Inserting into an empty cluster is no longer : the cluster's own minimum must be stored inside its sub-clusters too, so the insertion recurses all the way down. When the cluster of is empty, INSERT must insert its index into the summary (a real call) and insert into the empty cluster (now also a real call). So . With and : by the master theorem, so . Keeping the minimum out of the recursion is exactly what makes one of the two calls (Van Emde Boas Trees).
Exercise 2: Lookups in an x-fast trie
How many hash-table lookups does a SUCCESSOR query in an x-fast trie make in the worst case for ? How many prefix entries does a trie with random 64-bit keys store, approximately?
Answer
lookups. About entries, roughly 47 million.
Solution
The binary search runs over the prefix lengths ; each lookup halves the candidate range, so lookups in the worst case. For the space: the top levels of the trie are nearly complete, so they hold about prefixes in total; below that, the paths of random keys no longer share prefixes, and each key contributes its own entries plus the leaf. That is about entries, a factor more than the keys themselves, which is what the y-fast trie removes.
Exercise 3: The wrong bucket size
In a y-fast trie, what goes wrong if the buckets hold keys instead of ? And with ?
Answer
: the x-fast trie holds representatives of space each, space, and splits cost every updates, amortized. : everything still works, with bucket operations in a balanced BST; the space is either way.
Solution
The bucket size must satisfy two constraints: the x-fast trie's space must be , so ; and a bucket operation, in a balanced BST, must be , so is at most polynomial in . Updates must also amortize the cost of a split or merge over the updates between two of them, again requiring . With the first and third constraints fail. With they all hold, since . The usual choice is the smallest that works.
Exercise 4: Sketch four keys
Four 8-bit keys are stored in a fusion node: , , , . Find the branching bits, the sketches, and the rank that gives for . Is it correct?
Answer
Branching bits (from the right, bit 0 = least significant) ; sketches , , , (bits 6, 3, 2); , ranked after : rank 2, which is correct here ().
Solution
Adjacent keys first differ at: : bit 3; : bit 6; : bit 2. So the branching bits are 2, 3 and 6, and a sketch reads bits of a key. The program checks the sketches, compares the sketch rank with the true rank for every 8-bit , and counts how often the sketch alone is wrong, which is why fusion trees need the desketch step.
keys = [0b00010110, 0b00011001, 0b01010000, 0b01010111]
bits = sorted({(a ^ b).bit_length() - 1 for a, b in zip(keys, keys[1:])})
def sketch(x):
return sum(((x >> b) & 1) << i for i, b in enumerate(bits))
print("branching bits:", bits)
print("sketches:", [format(sketch(x), "03b") for x in keys])
y = 0b00011111
sk_rank = sum(sketch(x) <= sketch(y) for x in keys)
print(f"y = {y:08b}: sketch {sketch(y):03b}, sketch rank {sk_rank}, true rank {sum(x <= y for x in keys)}")
wrong = sum(sum(sketch(x) <= sketch(v) for x in keys) != sum(x <= v for x in keys) for v in range(256))
print(f"the sketch rank alone is wrong for {wrong} of the 256 possible queries")branching bits: [2, 3, 6]
sketches: ['001', '010', '100', '101']
y = 00011111: sketch 011, sketch rank 2, true rank 2
the sketch rank alone is wrong for 138 of the 256 possible queries
Exercise 5: Tours after LINK and CUT
A forest has the trees and (paths). Write an Euler tour of each (in the representation of the lesson, with vertex entries and directed edge entries), then the tour after LINK, and the two tours after CUT.
Answer
Tours and . After LINK (rerooted at and ): . After CUT: and .
Solution
LINK reroots 's tour at (rotation: ) and 's tour at (already), then concatenates tour(), , tour(), . Every tour has entries for vertices: here. CUT locates and ; the part strictly between them, , is 's side, and the rest, concatenated, is , with entries. Each step is splits and concatenations of balanced BSTs, (Euler-Tour Trees).
Exercise 6: Lowest common ancestors with ACCESS
Show how to compute the lowest common ancestor of and in a rooted forest with a link-cut tree, using two ACCESS operations.
Answer
ACCESS, then ACCESS; the LCA is the last node at which ACCESS jumped onto the preferred path containing the root, i.e. the last node splayed in the loop before the final splay (if and are in the same tree).
Solution
After ACCESS, the root-to- path is one preferred path. ACCESS walks up from through path-parent pointers. The walk ends on the root's preferred path, which is (the upper part of) the root-to- path, and it enters that path at the deepest node of the root-to- path that is also an ancestor of : the lowest common ancestor. In the loop of the lesson's access, that is the last value of y before y becomes NIL. Both ACCESS calls are amortized, so LCA queries are amortized, even while the forest changes by LINK and CUT. (If the last splayed node is not in 's tree, and are in different trees.)
Exercise 7: How high can an edge climb?
In the Holm-de Lichtenberg-Thorup algorithm, prove that no edge ever needs a level above .
Answer
By the size invariant, components of have at most vertices. An edge of level lies in a component of with at least 2 vertices, so , i.e. .
Solution
The algorithm raises edges of a tree of to level only when is the smaller half of a split tree, so , and it raises non-tree edges only when both ends are in such a . This maintains the invariant that every component of has at most vertices. An edge at level has both endpoints in one component of , which then has at least 2 vertices: , so . Since levels only increase, each edge is raised at most times, which gives the amortized update bound (Fully Dynamic Connectivity).
Exercise 8: Paths in a persistent tree
A persistent (path-copying) unbalanced BST receives keys in random order, keeping every version. Estimate the total number of nodes created, and compare with the expected depth of a random BST.
Answer
Each insertion copies its search path: about the depth of the new node plus one. The expected depth of the -th inserted key is about , so the total is a little below nodes, about 360000.
Solution
The program counts exactly. The average copied path is close to , matching the expected depth of a node in a random BST (The Expected Height of a Random BST analyses the same quantity).
import math, random
def insert(t, k, made): # t = (key, left, right) or None; returns a new root
if t is None:
made[0] += 1; return (k, None, None)
made[0] += 1
if k < t[0]: return (t[0], insert(t[1], k, made), t[2])
return (t[0], t[1], insert(t[2], k, made))
rng = random.Random(8)
n = 20000
keys = rng.sample(range(10 ** 6), n)
t, made = None, [0]
for k in keys:
t = insert(t, k, made)
print(f"{made[0]} nodes created, {made[0] / n:.1f} per insertion; 2 ln n = {2 * math.log(n):.1f}")355721 nodes created, 17.8 per insertion; 2 ln n = 19.8
The measured 17.8 is a little below : the average depth of a node in a random BST is about , and each insertion copies the path plus the new leaf. All 20000 versions together use about 18 nodes per key, against per key if every version were copied in full.
Exercise 9: A retroactive register
A register supports the update SET and the query GET. Design a fully retroactive version: insert or delete a SET at any time , and GET at any time . What does it cost?
Answer
Keep the SET operations in a balanced BST keyed by time. GET is the value of the SET with the largest time : a predecessor query. All operations are worst case.
Solution
The state at time depends only on the last SET before , so a retroactive change affects only the interval until the next SET, and nothing has to be propagated: storing the operations sorted by time is enough. INSERT and DELETE are BST insertions and deletions, GET a predecessor search, all (or with a van Emde Boas tree over integer times). The register is easy because SET overwrites the state; contrast it with the operations "" of the lower bound in Retroactive Data Structures, where every operation depends on the whole history.
Exercise 10: Passes of an external sort
Sort items (64-bit keys, 512 GiB) with words of memory and blocks of words. How many merge passes does multiway merge sort need, how many I/Os in total, and how does that compare with two-way merging?
Answer
runs, fan-in : one merge pass. Total million I/Os. Two-way merging needs passes: million.
Solution
import math
N, M, B = 2 ** 36, 2 ** 30, 2 ** 16
runs = N // M
for k in [2, M // B - 1]:
passes = math.ceil(math.log(runs, k) - 1e-9)
ios = 2 * (N // B) * (1 + passes)
print(f"fan-in {k:5}: {runs} runs, {passes} merge passes, {ios:>10} I/Os = {ios / (N // B):.0f} scans")
print(f"sort(N) = (N/B) log_(M/B)(N/B) = {(N / B) * math.log(N / B, M / B):.0f}")fan-in 2: 64 runs, 6 merge passes, 14680064 I/Os = 14 scans
fan-in 16383: 64 runs, 1 merge passes, 4194304 I/Os = 4 scans
sort(N) = (N/B) log_(M/B)(N/B) = 1497966
With realistic parameters the logarithm in is between 1 and 2 (), so external sorting costs a small constant number of scans; the constant 4 includes reading and writing in both passes (Sorting in External Memory).
Exercise 11: Searching a billion keys
For keys and blocks of keys (a 512-byte line of 64-bit keys), estimate the blocks touched by a search with a cold cache for (a) binary search on a sorted array, (b) a B-tree with nodes of keys, (c) the van Emde Boas layout (use the lesson's bound and its measured constant).
Answer
(a) ; (b) ; (c) at most by the worst-case analysis, about to to in practice.
Solution
(a) Binary search only saves the last steps of its , which fall inside one block: blocks. (b) A B-tree has height and reads one block per level. (c) The vEB layout's pieces of at most nodes have height at least about , a path crosses about of them, and each piece spans at most 2 blocks: at most 20 blocks. The worst case assumes every piece straddles a boundary and that pieces are as small as allowed; the measurements in The van Emde Boas Layout came out at 1.2 to 1.5 times , so about 6 to 8 blocks, for every at once.
Exercise 12: Rank and select by hand
For (positions 0 to 15, left to right), compute , , and . Then show how can be computed with rank queries.
Answer
, , , . Binary search for the smallest with .
Solution
The ones are at positions 1, 2, 4, 7, 8, 9, 11, 15 and the zeros at 0, 3, 5, 6, 10, 12, 13, 14. Positions 0 to 7 contain the ones 1, 2, 4, 7: and . The fifth one is at position 8, and the zeros at 0, 3, 5 make position 5 the third zero: and . Since is non-decreasing in , the position of the -th one is the smallest with , found by binary search with rank queries, each (Rank and Select on Bit Vectors).
b = [int(c) for c in "0110100111010001"]
rank1 = lambda i: sum(b[:i])
def select(bit, k):
lo, hi = 0, len(b) - 1 # smallest i with rank_bit(i + 1) >= k
while lo < hi:
mid = (lo + hi) // 2
r = rank1(mid + 1) if bit else (mid + 1) - rank1(mid + 1)
if r >= k: hi = mid
else: lo = mid + 1
return lo
print("rank1(8) =", rank1(8), " rank0(8) =", 8 - rank1(8), " select1(5) =", select(1, 5), " select0(3) =", select(0, 3))rank1(8) = 4 rank0(8) = 4 select1(5) = 8 select0(3) = 5
Exercise 13: Merging Bloom filters
Two Bloom filters with the same , and hash functions represent sets and . Show that their bitwise OR is exactly the Bloom filter of . Is their bitwise AND the filter of ?
Answer
OR: yes, exactly, since a bit is set in the filter of iff some element of or of sets it. AND: no; it can have more bits set than the filter of , so it is a valid filter for (no false negatives) but with a higher false-positive rate.
Solution
Bit of the filter of a set is . For this disjunction splits into the one over OR the one over . For AND, a bit can be set in both filters by different elements (one in , one in ), so the AND has every bit of the filter of and possibly more. The program checks both facts.
import random
def bloom(S, m, k, seed=5):
bits = [0] * m
for x in S:
r = random.Random(x * 1000003 + seed) # k fixed positions per element
for _ in range(k): bits[r.randrange(m)] = 1
return bits
rng = random.Random(13)
A = set(rng.sample(range(10000), 300))
B = set(rng.sample(range(10000), 300))
m, k = 4000, 5
fa, fb = bloom(A, m, k), bloom(B, m, k)
OR = [x | y for x, y in zip(fa, fb)]
AND = [x & y for x, y in zip(fa, fb)]
print("OR == filter(A | B):", OR == bloom(A | B, m, k))
print(f"|A & B| = {len(A & B)}; bits set: AND {sum(AND)}, filter(A & B) {sum(bloom(A & B, m, k))}")OR == filter(A | B): True
|A & B| = 7; bits set: AND 418, filter(A & B) 35
Exercise 14: Cuckoo graph cycles
Keys have hash values in two tables of 2 slots each. Can they all be stored? Add a key with : can all four be stored? And a fifth key with ?
Answer
Three keys: yes. Four: yes (the component has 4 vertices and 4 edges, one cycle). Five: no (5 edges on 4 vertices, two cycles), so INSERT fails and forces a rehash.
Solution
The cuckoo graph has vertices and an edge per key. form the 4-cycle : 4 edges on 4 vertices, exactly one cycle, so each key gets its own slot (for instance , , , ). A fifth key adds a fifth edge to a component with 4 vertices: there are only 4 slots, so no placement exists, and an insertion would loop until MAX-LOOP and trigger a rehash with new hash functions (Cuckoo Hashing).
Exercise 15: Backward search by hand
The BWT of is , and , , , . Run backward search for and give the number of occurrences.
Answer
Intervals: start ; after "a": ; after "n": ; after "a": . Two occurrences.
Solution
counts in with .
- : , . Rows 1 to 3 are the suffixes , , .
- : , . Rows 5, 6: , .
- : , . Rows 2, 3: and .
So "ana" occurs times (at positions 1 and 3, overlapping), found with rank queries (The FM-Index).
Test yourself
A van Emde Boas tree that also stores each structure's minimum inside its clusters makes two non-trivial recursive calls per INSERT. What does its running time become?
- , from
Two Bloom filters with the same , and hash functions represent and . What is their bitwise OR?
- Exactly the Bloom filter of
- The Bloom filter of
- A filter of with false negatives
- Nothing meaningful
In the HDT dynamic connectivity algorithm, why can no edge reach a level above ?
- Levels are reset after each deletion
- Components of have at most vertices, and an edge of level needs a component with at least 2 vertices
- Each edge is scanned only once
- The Euler-tour trees have height