TExcelTAD
Home › Advanced & Succinct Data Structures › Van Emde Boas Trees: Analysis and Space

Van Emde Boas Trees: Analysis and Space

The van Emde Boas tree answers every query in O(lg⁡lg⁡U)O(\lg \lg U) 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 Θ(U)\Theta(U) words even when it stores three keys. For U=264U = 2^{64} 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 O(n)O(n) in two steps: hashing and indirection.

The time bound, precisely

Let T(U)T(U) be the worst-case time of INSERT, DELETE, SUCCESSOR or PREDECESSOR on a universe of size U=2kU = 2^k. Each operation does O(1)O(1) work at its own level and makes at most one call that is not O(1)O(1), on a universe of size 2⌈k/2⌉2^{\lceil k/2 \rceil} (the summary or a cluster). With S(k)=T(2k)S(k) = T(2^k):

S(k)≤S(⌈k/2⌉)+c⟹S(k)≤c⌈lg⁡k⌉+S(1)=O(lg⁡lg⁡U)S(k) \le S(\lceil k/2 \rceil) + c \quad\Longrightarrow\quad S(k) \le c \lceil \lg k \rceil + S(1) = O(\lg \lg U)

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 a min field.
  • INSERT calls the summary only when the cluster was empty, and then the cluster insert is the O(1)O(1) "set min and max" case.
  • DELETE calls the summary only when the cluster became empty, and then the cluster delete was the O(1)O(1) "only one element" case.

The space bound of the array version

The array version stores, at a node of universe UU, the fields min and max, an array of U\sqrt{U} pointers, the summary (universe U\sqrt{U}) and U\sqrt{U} clusters (universe U\sqrt{U}). Its space satisfies

P(U)=(U+1) P(U)+Θ(U)P(U) = (\sqrt{U} + 1) \, P(\sqrt{U}) + \Theta(\sqrt{U})

which solves to P(U)=Θ(U)P(U) = \Theta(U). Since every cluster exists from the start, creating the structure also takes Θ(U)\Theta(U) time. The program evaluates the recurrence for U=2kU = 2^k (splitting kk bits into a high half of ⌈k/2⌉\lceil k/2 \rceil and a low half of ⌊k/2⌋\lfloor k/2 \rfloor) and prints the words per universe element.

python · try it yourself
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 nn.

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 O(1)O(1) expected (or worst case with a dynamic perfect hashing scheme), so the time bound becomes O(lg⁡lg⁡U)O(\lg \lg U) 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 O(lg⁡lg⁡U)O(\lg \lg U) structures, and the total space is

O(nlg⁡lg⁡U)=O(nlg⁡w) wordsO(n \lg \lg U) = O(n \lg w) \text{ words}

Is that bound reached? The program counts the structures created by 4096 inserts, for random keys and for the keys 0,1,…,40950, 1, \ldots, 4095.

python · try it yourself
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 ww doubles: the lg⁡w\lg w factor is real.

Step 2: indirection removes the last factor

The fix is the standard indirection trick, which reappears in y-fast tries:

  1. Split the sorted keys into buckets of between 12lg⁡w\frac{1}{2} \lg w and 2lg⁡w2 \lg w consecutive keys. Each bucket is a small sorted array (or a balanced BST).
  2. Store one representative per bucket (say, its minimum) in the hashed vEB tree. There are O(n/lg⁡w)O(n / \lg w) representatives, so the vEB tree takes O(nlg⁡w⋅lg⁡w)=O(n)O(\frac{n}{\lg w} \cdot \lg w) = O(n) space, and the buckets take O(n)O(n).
  3. SUCCESSOR(x)(x): find the predecessor representative in the vEB tree (O(lg⁡w)O(\lg w)), then search its bucket and possibly the next one (O(lg⁡w)O(\lg w) with a scan, O(lg⁡lg⁡w)O(\lg \lg w) with binary search).
  4. INSERT and DELETE change one bucket in O(lg⁡w)O(\lg w) time. When a bucket grows beyond 2lg⁡w2 \lg w keys, split it in two; when it shrinks below 12lg⁡w\frac{1}{2} \lg w, merge it with a neighbour (and split again if needed). Each split or merge changes O(1)O(1) representatives, costing O(lg⁡w)O(\lg w) in the vEB tree, and happens only after Ω(lg⁡w)\Omega(\lg w) updates to that bucket, so the cost is O(1)O(1) amortized on top.

The result: O(n)O(n) space and O(lg⁡lg⁡U)O(\lg \lg U) time per operation, expected (hashing) and amortized (splits, merges and table resizing) for updates, and expected for queries.

python · try it yourself
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 U\sqrt{U} clusters Θ(U)\Theta(U), built in Θ(U)\Theta(U) time O(lg⁡lg⁡U)O(\lg \lg U) worst case
hash tables of non-empty clusters O(nlg⁡lg⁡U)O(n \lg \lg U) O(lg⁡lg⁡U)O(\lg \lg U) expected (updates also amortized)
hashing + buckets of Θ(lg⁡lg⁡U)\Theta(\lg \lg U) keys O(n)O(n) O(lg⁡lg⁡U)O(\lg \lg U) expected, updates amortized

Note: Mehlhorn and Näher (1990) gave the first O(n)O(n)-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 Θ(U)\Theta(U) space even when it stores few keys?

  1. It stores every key lg⁡U\lg U times
  2. It allocates all U\sqrt{U} clusters at every node, recursively, whether or not they are used
  3. Its summary has UU entries
  4. Its hash tables are oversized

With hash tables of non-empty clusters, why can one INSERT create Θ(lg⁡lg⁡U)\Theta(\lg \lg U) new structures?

  1. Because it rebuilds the summary
  2. 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
  3. Because hashing is randomized
  4. It cannot; it creates at most one

In the indirection step, why are buckets of size Θ(lg⁡w)\Theta(\lg w) the right choice?

  1. They fit in one cache line
  2. Searching or updating a bucket costs O(lg⁡w)O(\lg w), matching the vEB query, while the vEB tree only stores n/Θ(lg⁡w)n / \Theta(\lg w) representatives and so uses O(n)O(n) space
  3. They make the structure deterministic
  4. They avoid hashing