TExcelTAD
Home › Advanced & Succinct Data Structures › Van Emde Boas Trees

Van Emde Boas Trees

A predecessor structure stores a dynamic set S⊆{0,…,U−1}S \subseteq \{0, \ldots, U - 1\} and supports INSERT, DELETE, MEMBER, SUCCESSOR(x)(x) (the smallest element larger than xx) and PREDECESSOR(x)(x). A balanced BST does all of them in O(lg⁡n)O(\lg n). The van Emde Boas tree (van Emde Boas, 1975; the version here follows the later simplified presentations) does all of them in O(lg⁡lg⁡U)O(\lg \lg U) worst-case time, independent of nn. For 64-bit keys that is lg⁡64=6\lg 64 = 6 levels of recursion.

The idea: split the key in half

Write a ww-bit key xx as its top half and bottom half, x=⟨h,ℓ⟩x = \langle h, \ell \rangle with h=⌊x/U⌋h = \lfloor x / \sqrt{U} \rfloor and ℓ=x mod U\ell = x \bmod \sqrt{U} (for U=2wU = 2^w that is the top and bottom w/2w/2 bits). The universe splits into U\sqrt{U} clusters of U\sqrt{U} keys each, and xx lives at position ℓ\ell of cluster hh. A second structure, the summary, records which clusters are non-empty.

Before recursing, look at the flat version: a bit array split into U\sqrt{U} blocks plus one summary bit per block. Successor checks the rest of xx's own block, then scans the summary for the next non-empty block, then takes that block's first bit, O(U)O(\sqrt{U}) steps instead of O(U)O(U).

python · try it yourself
U, R = 64, 8                                   # R = sqrt(U) clusters of R bits
bits = [0] * U
summary = [0] * R
for x in [3, 9, 14, 40, 41, 63]:
    bits[x] = 1
    summary[x // R] = 1

def successor(x):
    steps = 0
    h, l = divmod(x, R)
    for j in range(l + 1, R):                  # rest of x's own cluster
        steps += 1
        if bits[h * R + j]: return h * R + j, steps
    for c in range(h + 1, R):                  # next non-empty cluster in the summary
        steps += 1
        if summary[c]:
            for j in range(R):                 # its first element
                steps += 1
                if bits[c * R + j]: return c * R + j, steps
    return None, steps

for c in range(R):
    print(f"cluster {c} (summary bit {summary[c]}):", "".join(map(str, bits[c * R:(c + 1) * R])))
for x in [3, 15, 41]:
    print(f"successor({x}) =", *successor(x), "steps")
cluster 0 (summary bit 1): 00010000
cluster 1 (summary bit 1): 01000010
cluster 2 (summary bit 0): 00000000
cluster 3 (summary bit 0): 00000000
cluster 4 (summary bit 0): 00000000
cluster 5 (summary bit 1): 11000000
cluster 6 (summary bit 0): 00000000
cluster 7 (summary bit 1): 00000001
successor(3) = 9 7 steps
successor(15) = 40 5 steps
successor(41) = 63 16 steps

The van Emde Boas tree makes each cluster and the summary themselves van Emde Boas trees over a universe of size U\sqrt{U}. Successor then has three parts: look inside xx's cluster, or ask the summary for the next non-empty cluster and take its minimum. If each part recursed, the running time would satisfy T(U)=2T(U)+O(1)T(U) = 2T(\sqrt{U}) + O(1), which solves to O(lg⁡U)O(\lg U), no better than a balanced tree. The structure gets O(lg⁡lg⁡U)O(\lg \lg U) by making sure that only one of the recursive calls is real.

Two rules that make one call enough

  1. Store the minimum and the maximum of each structure in two fields. Then "the minimum of the next non-empty cluster" is a field read, not a recursive call, and "is the answer inside xx's own cluster?" is a comparison with that cluster's maximum.
  2. Do not store the minimum recursively. The minimum of a structure lives only in its min field, not in any cluster. Inserting into an empty structure then just sets min = max = x in O(1)O(1). So when INSERT puts xx into an empty cluster, the call into the cluster is trivial and only the summary call does real work; when the cluster is not empty, the summary already knows about it and is not touched.

With both rules each operation makes at most one non-trivial recursive call on a universe of size U\sqrt{U}:

T(U)=T(U)+O(1)⟹T(U)=O(lg⁡lg⁡U)T(U) = T(\sqrt{U}) + O(1) \quad\Longrightarrow\quad T(U) = O(\lg \lg U)

Substituting m=lg⁡Um = \lg U turns it into S(m)=S(m/2)+O(1)S(m) = S(m/2) + O(1), which is O(lg⁡m)O(\lg m).

text
SUCCESSOR(V, x)                               // smallest element of V greater than x
1  if V.min != NIL and x < V.min
2      return V.min
3  if V.universe == 2                          // base case: keys 0 and 1
4      return 1 if x == 0 and V.max == 1 else NIL
5  h, l = high(x), low(x)
6  if cluster h exists and l < V.cluster[h].max
7      return index(h, SUCCESSOR(V.cluster[h], l))     // the one real call
8  c = SUCCESSOR(V.summary, h)                         // or this one, never both
9  if c == NIL
10     return NIL
11 return index(c, V.cluster[c].min)                    // a field read

INSERT(V, x)
1  if V.min == NIL
2      V.min = V.max = x; return               // O(1): nothing stored below
3  if x < V.min
4      swap(x, V.min)                          // the old minimum goes down instead
5  if V.universe > 2
6      h, l = high(x), low(x)
7      if cluster h is empty
8          INSERT(V.summary, h)                // the real call
9          V.cluster[h].min = V.cluster[h].max = l     // O(1)
10     else
11         INSERT(V.cluster[h], l)             // the real call
12 if x > V.max
13     V.max = x

An implementation that counts calls

The program implements MEMBER, INSERT, SUCCESSOR and DELETE. Clusters are created on demand in a dictionary (the textbook version allocates all U\sqrt{U} of them up front; the next lesson compares the two). A counter records how many method calls each operation makes in total, the recursive ones included. After 3000 random operations on 32-bit keys it checks every answer against a sorted list.

python · try it yourself
import bisect, random

class VEB:
    calls = 0
    def __init__(self, k):                     # universe {0, ..., 2^k - 1}
        self.k, self.min, self.max = k, None, None
        if k > 1:
            self.lo = k // 2                   # low half: k // 2 bits, high half: the rest
            self.clusters, self.summary = {}, None
    def _split(self, x):
        return x >> self.lo, x & ((1 << self.lo) - 1)
    def member(self, x):
        VEB.calls += 1
        if x == self.min or x == self.max: return True
        if self.k == 1: return False
        h, l = self._split(x)
        c = self.clusters.get(h)
        return c is not None and c.member(l)
    def insert(self, x):
        VEB.calls += 1
        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 = self._split(x)
            c = self.clusters.get(h)
            if c is None:                      # empty cluster: O(1) insert, real work in the summary
                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
    def successor(self, x):
        VEB.calls += 1
        if self.min is not None and x < self.min: return self.min
        if self.k == 1:
            return 1 if x == 0 and self.max == 1 else None
        h, l = self._split(x)
        c = self.clusters.get(h)
        if c is not None and l < c.max:
            return (h << self.lo) | c.successor(l)
        nxt = self.summary.successor(h) if self.summary else None
        return None if nxt is None else (nxt << self.lo) | self.clusters[nxt].min
    def delete(self, x):                       # x must be present
        VEB.calls += 1
        if self.min == self.max:
            self.min = self.max = None; return
        if self.k == 1:
            self.min = self.max = 1 - x; return
        if x == self.min:                      # pull the next element up to be the new min
            first = self.summary.min
            x = self.min = (first << self.lo) | self.clusters[first].min
        h, l = self._split(x)
        c = self.clusters[h]
        c.delete(l)
        if c.min is None:                      # cluster became empty: remove it from the summary
            del self.clusters[h]
            self.summary.delete(h)
            if self.summary.min is None: self.summary = None
        if x == self.max:
            if self.summary is None: self.max = self.min
            else:
                top = self.summary.max
                self.max = (top << self.lo) | self.clusters[top].max

rng = random.Random(1975)
k = 32
v, ref = VEB(k), []
worst = {"insert": 0, "delete": 0, "successor": 0, "member": 0}
for step in range(3000):
    op = rng.choice(["insert", "insert", "delete", "successor", "member"])
    from_set = ref and (op == "delete" or (op == "member" and rng.random() < 0.5))
    x = rng.choice(ref) if from_set else rng.randrange(1 << k)
    if op == "delete" and not ref: op = "insert"
    VEB.calls = 0
    if op == "insert":
        if not v.member(x):
            VEB.calls = 0; v.insert(x); bisect.insort(ref, x)
    elif op == "delete":
        v.delete(x); ref.remove(x)
    elif op == "successor":
        i = bisect.bisect_right(ref, x)
        assert v.successor(x) == (ref[i] if i < len(ref) else None)
    else:
        assert v.member(x) == (x in ref)
    worst[op] = max(worst[op], VEB.calls)
print("size at the end:", len(ref), " min/max agree:", (v.min, v.max) == ((ref[0], ref[-1]) if ref else (None, None)))
print("most calls made by one operation:", worst)
print("levels of recursion for w = 32: lg w + 1 =", k.bit_length())
size at the end: 604  min/max agree: True
most calls made by one operation: {'insert': 6, 'delete': 11, 'successor': 6, 'member': 2}
levels of recursion for w = 32: lg w + 1 = 6

The universe sizes along a chain of calls are 232,216,28,24,22,212^{32}, 2^{16}, 2^8, 2^4, 2^2, 2^1: six structures, and INSERT and SUCCESSOR never made more than six calls. MEMBER stops as soon as xx is the minimum or maximum of a structure, which in a sparse random set happens near the top. DELETE made up to 11 calls because, when it empties a cluster, it also calls DELETE on the summary. But a cluster that becomes empty held a single element, and that call returns at once at the min == max test. So at each level at most one of the two calls is real, the other costs O(1)O(1), and DELETE takes at most about 2(lg⁡w+1)2(\lg w + 1) calls: still O(lg⁡lg⁡U)O(\lg \lg U). That is the delete-side version of rule 2.

In C++

The same structure with std::unordered_map for the clusters. The program inserts the keys of the first example into a 16-bit universe and walks the set with SUCCESSOR, then deletes two keys and walks it again.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <memory>
#include <optional>
#include <unordered_map>

class VEB {
    int k, lo;
    std::optional<std::uint32_t> mn, mx;
    std::unordered_map<std::uint32_t, std::unique_ptr<VEB>> clusters;
    std::unique_ptr<VEB> summary;
    std::uint32_t high(std::uint32_t x) const { return x >> lo; }
    std::uint32_t low(std::uint32_t x) const { return x & ((1u << lo) - 1); }
    std::uint32_t index(std::uint32_t h, std::uint32_t l) const { return (h << lo) | l; }
public:
    explicit VEB(int bits) : k(bits), lo(bits / 2) {}
    bool empty() const { return !mn; }
    std::optional<std::uint32_t> min() const { return mn; }
    void insert(std::uint32_t x) {
        if (!mn) { mn = mx = x; return; }
        if (x < *mn) std::swap(x, *mn);
        if (k > 1) {
            auto h = high(x), l = low(x);
            auto it = clusters.find(h);
            if (it == clusters.end()) {
                auto c = std::make_unique<VEB>(lo);
                c->mn = c->mx = l;
                clusters.emplace(h, std::move(c));
                if (!summary) summary = std::make_unique<VEB>(k - lo);
                summary->insert(h);
            } else {
                it->second->insert(l);
            }
        }
        if (x > *mx) mx = x;
    }
    std::optional<std::uint32_t> successor(std::uint32_t x) const {
        if (mn && x < *mn) return mn;
        if (k == 1) return (x == 0 && mx && *mx == 1) ? std::optional<std::uint32_t>(1) : std::nullopt;
        auto h = high(x), l = low(x);
        auto it = clusters.find(h);
        if (it != clusters.end() && l < *it->second->mx) return index(h, *it->second->successor(l));
        if (!summary) return std::nullopt;
        auto c = summary->successor(h);
        if (!c) return std::nullopt;
        return index(*c, *clusters.at(*c)->mn);
    }
    void erase(std::uint32_t x) {                       // x must be present
        if (*mn == *mx) { mn.reset(); mx.reset(); return; }
        if (k == 1) { mn = mx = 1 - x; return; }
        if (x == *mn) {
            auto first = *summary->mn;
            x = index(first, *clusters.at(first)->mn);
            mn = x;
        }
        auto h = high(x), l = low(x);
        auto& c = clusters.at(h);
        c->erase(l);
        if (c->empty()) {
            clusters.erase(h);
            summary->erase(h);
            if (summary->empty()) summary.reset();
        }
        if (x == *mx) {
            if (!summary) mx = mn;
            else { auto top = *summary->mx; mx = index(top, *clusters.at(top)->mx); }
        }
    }
};

void walk(const VEB& v) {
    std::printf("set:");
    for (auto x = v.min(); x; x = v.successor(*x)) std::printf(" %u", *x);
    std::printf("\n");
}

int main() {
    VEB v(16);
    for (std::uint32_t x : {40u, 3u, 63u, 9u, 41u, 14u, 65535u, 1000u}) v.insert(x);
    walk(v);
    std::printf("successor(15) = %u, successor(41) = %u\n", *v.successor(15), *v.successor(41));
    v.erase(3);
    v.erase(65535);
    walk(v);
    std::printf("successor(1000) is %s\n", v.successor(1000) ? "present" : "none");
}
set: 3 9 14 40 41 63 1000 65535
successor(15) = 40, successor(41) = 63
set: 9 14 40 41 63 1000
successor(1000) is none

PREDECESSOR is symmetric (swap min with max and the directions of the comparisons), with one extra case: because the minimum is not stored in the clusters, if the summary has no non-empty cluster before hh, the answer may still be V.min.

Test yourself

Without the rule "store min and max in fields", successor would make two recursive calls. What would its running time be?

  1. O(lg⁡lg⁡U)O(\lg \lg U)
  2. O(lg⁡U)O(\lg U)
  3. O(U)O(\sqrt{U})
  4. O(1)O(1)

Why does INSERT into an empty cluster cost only O(1)O(1)?

  1. Empty clusters are cached
  2. The minimum of a structure is stored only in its min field, so inserting into an empty structure just sets min and max
  3. The summary does the insert
  4. Clusters have size 2

For U=264U = 2^{64}, how many universe sizes does one chain of recursive calls pass through, from 2642^{64} down to the base case 212^1?

  1. 4
  2. 7
  3. 32
  4. 64