Van Emde Boas Trees: Analysis and Space
The van Emde Boas tree answers every query in time, but the textbook version pays for it in space: it allocates a cluster for every possible high half, whether or not any key uses it, so it needs words even when it stores three keys. For that is not a data structure but a thought experiment. This lesson proves the time and space bounds and then brings the space down to in two steps: hashing and indirection.
The time bound, precisely
Let be the worst-case time of INSERT, DELETE, SUCCESSOR or PREDECESSOR on a universe of size . Each operation does work at its own level and makes at most one call that is not , on a universe of size (the summary or a cluster). With :
The bound is worst case and deterministic for the array version. Every claim of "one real call" in the code was a case analysis:
- SUCCESSOR calls either the cluster (when the answer is inside it, detected by comparing with the cluster's
max) or the summary, then reads aminfield. - INSERT calls the summary only when the cluster was empty, and then the cluster insert is the "set min and max" case.
- DELETE calls the summary only when the cluster became empty, and then the cluster delete was the "only one element" case.
The space bound of the array version
The array version stores, at a node of universe , the fields min and max, an array of pointers, the summary (universe ) and clusters (universe ). Its space satisfies
which solves to . Since every cluster exists from the start, creating the structure also takes time. The program evaluates the recurrence for (splitting bits into a high half of and a low half of ) and prints the words per universe element.
from functools import lru_cache
@lru_cache(maxsize=None)
def words(k):
"""Words used by an array-based vEB tree over 2^k keys: min, max, pointers, summary, clusters."""
if k == 1:
return 2 # min and max only
hi, lo = k - k // 2, k // 2
return 2 + (1 << hi) + words(hi) + (1 << hi) * words(lo)
for k in [2, 4, 8, 16, 24, 32]:
w = words(k)
print(f"U = 2^{k:<2}: {w:>14} words, {w / 2 ** k:.3f} words per possible key")U = 2^2 : 10 words, 2.500 words per possible key
U = 2^4 : 56 words, 3.500 words per possible key
U = 2^8 : 970 words, 3.789 words per possible key
U = 2^16: 249548 words, 3.808 words per possible key
U = 2^24: 60459430 words, 3.604 words per possible key
U = 2^32: 16354692814 words, 3.808 words per possible key
Between 3.5 and 3.9 words per possible key: 16 billion words (over 100 GB) for 32-bit keys, regardless of .
Step 1: only non-empty clusters, in a hash table
Keep the clusters of each node in a hash table keyed by the high half, and create a cluster (or the summary) only when something is inserted into it. That is what the implementation in the previous lesson did with a Python dict. Lookups now cost expected (or worst case with a dynamic perfect hashing scheme), so the time bound becomes expected per operation, and updates are expected and amortized because of table resizing.
How much space does this use? A structure exists only if it is non-empty. INSERT creates a new structure only on its path of calls: at each level it creates at most one new cluster (when the cluster was empty) plus perhaps a new summary, and continues into the summary. So one insert creates structures, and the total space is
Is that bound reached? The program counts the structures created by 4096 inserts, for random keys and for the keys .
import random
class VEB:
made = 0
def __init__(self, k):
VEB.made += 1
self.k, self.min, self.max = k, None, None
if k > 1:
self.lo, self.clusters, self.summary = k // 2, {}, None
def insert(self, x):
if self.min is None:
self.min = self.max = x; return
if x < self.min: x, self.min = self.min, x
if self.k > 1:
h, l = x >> self.lo, x & ((1 << self.lo) - 1)
c = self.clusters.get(h)
if c is None:
c = self.clusters[h] = VEB(self.lo); c.min = c.max = l
if self.summary is None: self.summary = VEB(self.k - self.lo)
self.summary.insert(h)
else:
c.insert(l)
if x > self.max: self.max = x
rng = random.Random(5)
for k in [16, 32, 64]:
random_keys = sorted({rng.randrange(1 << k) for _ in range(4096)})
for name, keys in [("random", random_keys), ("0..4095", list(range(4096)))]:
VEB.made = 0
v, worst = VEB(k), 0
for x in keys:
before = VEB.made
v.insert(x)
worst = max(worst, VEB.made - before)
print(f"w = {k:2}, {name:8} keys: {VEB.made / len(keys):.2f} structures per key, at most {worst} created by one insert")w = 16, random keys: 2.41 structures per key, at most 5 created by one insert
w = 16, 0..4095 keys: 1.34 structures per key, at most 4 created by one insert
w = 32, random keys: 3.36 structures per key, at most 6 created by one insert
w = 32, 0..4095 keys: 1.34 structures per key, at most 4 created by one insert
w = 64, random keys: 4.37 structures per key, at most 7 created by one insert
w = 64, 0..4095 keys: 1.34 structures per key, at most 4 created by one insert
For dense keys the clusters are shared and the space is linear. For spread-out random keys each insert starts a fresh chain of nearly empty structures, and the count per key grows by about one each time doubles: the factor is real.
Step 2: indirection removes the last factor
The fix is the standard indirection trick, which reappears in y-fast tries:
- Split the sorted keys into buckets of between and consecutive keys. Each bucket is a small sorted array (or a balanced BST).
- Store one representative per bucket (say, its minimum) in the hashed vEB tree. There are representatives, so the vEB tree takes space, and the buckets take .
- SUCCESSOR: find the predecessor representative in the vEB tree (), then search its bucket and possibly the next one ( with a scan, with binary search).
- INSERT and DELETE change one bucket in time. When a bucket grows beyond keys, split it in two; when it shrinks below , merge it with a neighbour (and split again if needed). Each split or merge changes representatives, costing in the vEB tree, and happens only after updates to that bucket, so the cost is amortized on top.
The result: space and time per operation, expected (hashing) and amortized (splits, merges and table resizing) for updates, and expected for queries.
import bisect, random
def bucketize(keys, lo, hi):
"""Greedy split of sorted keys into buckets of size in [lo, hi]; representative = bucket minimum."""
buckets, i = [], 0
while i < len(keys):
size = min(hi, len(keys) - i)
if 0 < len(keys) - i - size < lo: # keep the last bucket from being too small
size = (len(keys) - i) // 2
buckets.append(keys[i:i + size]); i += size
return buckets
rng = random.Random(11)
w = 64
lgw = w.bit_length() - 1 # lg w = 6
keys = sorted({rng.randrange(1 << w) for _ in range(5000)})
buckets = bucketize(keys, lgw // 2, 2 * lgw)
reps = [b[0] for b in buckets]
print(f"n = {len(keys)}, lg w = {lgw}, buckets: {len(buckets)}, sizes {min(map(len, buckets))}..{max(map(len, buckets))}")
print(f"hashed vEB over representatives: about {4.37 * len(reps):.0f} structures, i.e. {4.37 * len(reps) / len(keys):.2f} per key")
def successor(x):
i = bisect.bisect_right(reps, x) - 1 # predecessor representative: the vEB query
for b in buckets[max(i, 0):i + 2]: # its bucket, then the next one
for y in b:
if y > x: return y
return None
qs = [rng.randrange(1 << w) for _ in range(2000)]
assert all(successor(q) == (keys[j] if (j := bisect.bisect_right(keys, q)) < len(keys) else None) for q in qs)
print("2000 successor queries agree with binary search on all keys")n = 5000, lg w = 6, buckets: 417, sizes 8..12
hashed vEB over representatives: about 1822 structures, i.e. 0.36 per key
2000 successor queries agree with binary search on all keys
The estimate in the second line reuses the 4.37 structures per key measured above for random 64-bit keys; with one key in twelve going into the vEB tree, the tree costs about a third of a structure per stored key.
Summary of the variants
| Variant | Space (words) | Time per operation |
|---|---|---|
| arrays of all clusters | , built in time | worst case |
| hash tables of non-empty clusters | expected (updates also amortized) | |
| hashing + buckets of keys | expected, updates amortized |
Note: Mehlhorn and Näher (1990) gave the first -space version using hashing. Willard's y-fast trie (1983) reached the same bounds in a different way; it is the one usually taught, and the next two lessons build it.
Test yourself
Why does the array version of a vEB tree use space even when it stores few keys?
- It stores every key times
- It allocates all clusters at every node, recursively, whether or not they are used
- Its summary has entries
- Its hash tables are oversized
With hash tables of non-empty clusters, why can one INSERT create new structures?
- Because it rebuilds the summary
- Because at each level of its call chain it may create a new cluster and continue into the summary, which may need a new cluster too
- Because hashing is randomized
- It cannot; it creates at most one
In the indirection step, why are buckets of size the right choice?
- They fit in one cache line
- Searching or updating a bucket costs , matching the vEB query, while the vEB tree only stores representatives and so uses space
- They make the structure deterministic
- They avoid hashing