Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

van Emde Boas Trees & Integer Priority Queues

O(log log U) operations on integer keys.

No comparison-based priority queue can make both insert and extract-min faster than logarithmic, because it could then sort. But the keys in real programs are machine integers, and an integer can be cut in half by its bits. Peter van Emde Boas's 1975 tree does this recursively and answers insert, delete and successor in O(log⁡log⁡U)O(\log\log U) time: six halvings for 64-bit keys, however many keys are stored.

What you’ll learn

  • State the word-RAM model and explain why comparison lower bounds do not apply to integer keys.
  • Describe a van Emde Boas tree (minimum kept aside, U\sqrt U clusters, a summary) and prove O(log⁡log⁡U)O(\log\log U) time for insert, successor and delete from T(U)=T(U)+O(1)T(U) = T(\sqrt U) + O(1).
  • Reduce its space from Θ(U)\Theta(U) to O(nlog⁡log⁡U)O(n\log\log U) with hashing, and to O(n)O(n) with indirection, as in y-fast tries.
  • Implement a radix heap for monotone priority queues and use it in Dijkstra's algorithm with integer weights.
  • State the landmark results: integer priority queues are equivalent to integer sorting (Thorup), and predecessor search has matching lower bounds.

Integers are more than comparable

In the word RAM, keys are ww-bit integers from the universe {0,…,U−1}\{0, \dots, U-1\}, U=2wU = 2^w, with w≥log⁡2nw \ge \log_2 n, and arithmetic, shifts and bitwise operations on whole words take O(1)O(1) time. An algorithm may also use a key as an array index. The lower bound "insert plus extract-min costs log⁡2n−O(1)\log_2 n - O(1) comparisons" covers only algorithms that learn about keys by comparing them; an algorithm that looks at bits can escape it.

The simplest example is a bucket queue (Dial, 1969): an array of buckets indexed by key. Insert is O(1)O(1), and in a monotone queue, where extracted keys never decrease, extract-min scans forward from the last minimum. When all keys lie within CC of the current minimum, as in Dijkstra's algorithm with integer weights at most CC, a cyclic array of C+1C+1 buckets suffices and the whole run costs O(m+nC)O(m + nC).

StructureOperationsTime per operationSpace
Bucket queue (Dial, 1969)monotone insert, extract-minO(1)O(1) insert; scans for the minimumO(C)O(C)
van Emde Boas tree (1975)insert, delete, min, successor, predecessorO(log⁡log⁡U)O(\log\log U) worst caseO(U)O(U); O(n)O(n) with hashing and indirection
Radix heap (Ahuja, Mehlhorn, Orlin & Tarjan, 1990)monotone insert, decrease-key, extract-minO(log⁡C)O(\log C) amortized extract-minO(n+log⁡C)O(n + \log C)
Fusion tree (Fredman & Willard, 1993)insert, delete, predecessorO(log⁡wn)O(\log_w n)O(n)O(n)
Thorup (2004)insert, decrease-key, deleteO(1)O(1), O(1)O(1), O(log⁡log⁡n)O(\log\log n), deterministicO(n)O(n)
Integer priority queues on the word RAM. UU is the universe size and CC the largest edge weight. The last row's queue gives Dijkstra's algorithm O(m+nlog⁡log⁡n)O(m + n\log\log n) time on directed graphs with integer weights.

van Emde Boas trees

python
class VEB:                                     # a set of w-bit integers
    def __init__(self, w):
        self.w, self.min, self.max = w, None, None
        self.lo = w // 2                       # bits of the position inside a cluster
        self.summary, self.cluster = None, {}  # only non-empty clusters are stored

    def insert(self, x):                       # O(log w) = O(log log U); x not yet present
        if self.min is None:
            self.min = self.max = x            # empty structure: O(1)
            return
        if x < self.min:
            x, self.min = self.min, x          # the minimum stays here; push the old one down
        if self.w > 1:
            h, l = x >> self.lo, x & ((1 << self.lo) - 1)
            if h not in self.cluster:          # empty cluster: fill it in O(1) ...
                self.cluster[h] = c = VEB(self.lo)
                c.min = c.max = l
                self.summary = self.summary or VEB(self.w - self.lo)
                self.summary.insert(h)         # ... and recurse into the summary only
            else:
                self.cluster[h].insert(l)      # otherwise recurse into the cluster only
        self.max = max(self.max, x)

    def successor(self, x):                    # smallest key > x, or None
        if self.w == 1:
            return 1 if x == 0 and self.max == 1 else None
        if self.min is not None and x < self.min:
            return self.min
        h, l = x >> self.lo, x & ((1 << self.lo) - 1)
        c = self.cluster.get(h)
        if c is not None and l < c.max:        # the answer is in x's own cluster
            return (h << self.lo) | c.successor(l)
        s = self.summary.successor(h) if self.summary else None
        return None if s is None else (s << self.lo) | self.cluster[s].min

Clusters live in a dictionary, so only non-empty ones take space. Delete follows the same pattern and is left out; the classic version, with arrays of clusters, is in Cormen et al. (3rd ed., chapter 20).

DerivationOne real recursive call per level
  1. T(U)=T(U)+O(1)T(U) = T(\sqrt U) + O(1)

    Successor. If xx is below the minimum, answer at once. Otherwise the cluster's stored maximum says in O(1)O(1) whether the answer lies in xx's own cluster: if so, recurse there; if not, recurse into the summary for the next non-empty cluster and return its stored minimum. Either way, one call on a universe of size U\sqrt U:

  2. Tinsert(U)=Tinsert(U)+O(1)T_{\text{insert}}(U) = T_{\text{insert}}(\sqrt U) + O(1)

    Insert. Because the minimum is kept outside the clusters, an empty structure takes its first key in O(1)O(1). So when xx's cluster is empty, only the summary insert recurses, and when it is not empty, the summary needs no change and only the cluster insert recurses. The same recurrence holds.

  3. S(w)=S(w/2)+O(1)=O(log⁡w)=O(log⁡log⁡U)S(w) = S(w/2) + O(1) = O(\log w) = O(\log\log U)

    Solve it in terms of the word size: U=2w/2\sqrt U = 2^{w/2}, so with S(w)=T(2w)S(w) = T(2^w) each call halves the number of bits.

  4. Tdelete(U)=Tdelete(U)+O(1)T_{\text{delete}}(U) = T_{\text{delete}}(\sqrt U) + O(1)

    Delete is symmetric: deleting the minimum pulls the next key up from the first non-empty cluster, and a cluster that becomes empty has its index deleted from the summary, which is the only real recursion because deleting from a one-key structure is O(1)O(1). As a priority queue, find-min is O(1)O(1) and extract-min and decrease-key cost O(log⁡log⁡U)O(\log\log U); duplicate keys need a count per key.

Predict before you look

A successor query in a vEB tree over 64-bit keys halves the word size at each recursive call. How many recursive calls can it make before reaching the 1-bit base case?

Show the answer

6

64→32→16→8→4→2→164 \to 32 \to 16 \to 8 \to 4 \to 2 \to 1: six halvings, since log⁡264=6\log_2 64 = 6. Binary search over a million sorted keys needs 20 comparisons, and a balanced BST about as many; the vEB tree's cost does not depend on nn at all, only on the word size.

From Θ(U) space to O(n)

The textbook vEB tree stores an array of U\sqrt U cluster pointers in every structure, so its space satisfies S(U)=(U+1) S(U)+Θ(U)=Θ(U)S(U) = (\sqrt U + 1)\,S(\sqrt U) + \Theta(\sqrt U) = \Theta(U). That is fine for U=216U = 2^{16} and absurd for U=264U = 2^{64}.

Hashing. Keep only the non-empty clusters, in a hash table, as the code above does with a dictionary. An insertion creates at most one new structure per level of recursion, and there are O(log⁡log⁡U)O(\log\log U) levels, so nn keys occupy O(nlog⁡log⁡U)O(n\log\log U) space; operations now run in O(log⁡log⁡U)O(\log\log U) expected time, or worst case with dynamic perfect hashing at the price of amortization.

Indirection. Sort the keys into buckets of Θ(log⁡U)\Theta(\log U) consecutive keys, each kept in a small balanced search tree, and insert only one representative per bucket into the vEB tree. The tree then holds O(n/log⁡U)O(n/\log U) keys and takes O(n)O(n) space, a query costs O(log⁡log⁡U)O(\log\log U) in the tree plus O(log⁡log⁡U)O(\log\log U) inside one bucket, and splitting or merging a bucket happens rarely enough to cost O(1)O(1) amortized per update. This is the trick of Willard's y-fast trie (1983), which applies it to a binary trie with hashed levels (see Binary Tries & Maximum XOR); Mehlhorn and Näher (1990) obtained O(n)O(n) space for van Emde Boas's structure itself.

Check your understanding

In insert, what makes it possible to recurse into only one substructure at each level?

  1. The summary is always empty when a cluster is non-empty
  2. An empty structure takes its first key as its stored minimum in O(1)O(1), without recursing, so a key landing in an empty cluster costs one recursive call into the summary, and otherwise the summary needs no change
  3. Clusters are stored in a hash table, which inserts in O(1)O(1)
  4. UU is a power of 2, so the high and low halves are independent
Show the answer

B. An empty structure takes its first key as its stored minimum in O(1)O(1), without recursing, so a key landing in an empty cluster costs one recursive call into the summary, and otherwise the summary needs no change

This is the reason the minimum is stored outside the clusters. If the minimum were also inserted recursively, a key arriving in an empty cluster would need two full recursive calls, one into the summary and one into the cluster, and the recurrence T(U)=2T(U)+O(1)T(U) = 2T(\sqrt U) + O(1) would give O(log⁡U)O(\log U) instead of O(log⁡log⁡U)O(\log\log U).

Monotone queues: radix heaps for Dijkstra

Dijkstra's priority queue is monotone: the extracted keys never decrease, and every inserted key, dist[u]+w(u,v)\mathrm{dist}[u] + w(u, v), is at least the last extracted one. A radix heap (Ahuja, Mehlhorn, Orlin & Tarjan, 1990) exploits exactly that. In the simple version below, popular in competitive programming, a key sits in bucket ii when the highest bit in which it differs from the last extracted key is bit i−1i - 1, and in bucket 0 when it equals that key.

python
class RadixHeap:          # monotone: every pushed key must be >= the last popped key
    def __init__(self, w=64):
        self.last = 0
        self.b = [[] for _ in range(w + 1)]   # b[i]: highest bit differing from last is i - 1

    def push(self, key):                       # O(1) actual
        self.b[(key ^ self.last).bit_length()].append(key)

    def pop(self):                             # O(w) amortized
        if not self.b[0]:
            i = 1
            while not self.b[i]:
                i += 1
            self.last = min(self.b[i])         # the new reference point
            for key in self.b[i]:              # each key drops to a lower bucket
                self.b[(key ^ self.last).bit_length()].append(key)
            self.b[i] = []
        return self.b[0].pop()                 # bucket 0 holds keys equal to last

A key enters one bucket and can only move down, so its total movement is O(w)O(w). For Dijkstra's algorithm, push pairs (key, vertex) keyed on the distance, and skip stale entries as with any lazy-deletion heap.

DerivationKeys only move down
  1. bitlen⁡(x⊕m) < i\operatorname{bitlen}(x \oplus m)\ <\ i

    A key xx in bucket i≥1i \ge 1 agrees with ℓ\ell, the last extracted key, on every bit above bit i−1i - 1, and has bit i−1i - 1 set where ℓ\ell has it clear, because x>ℓx > \ell. The new reference point mm, the bucket's minimum, has the same two properties, so xx and mm agree on every bit from i−1i - 1 upward:

  2. push: O(w) amortized,pop: O(w) amortized, including the scan for a non-empty bucket\text{push: } O(w) \text{ amortized}, \qquad \text{pop: } O(w) \text{ amortized, including the scan for a non-empty bucket}

    So each redistribution sends every key of bucket ii to a strictly lower bucket, and a key moves at most ww times before it reaches bucket 0. Charging the moves to the key's insertion:

  3. O(m+nlog⁡C),O(m+nlog⁡C) when combined with a Fibonacci heapO(m + n\log C), \qquad O\big(m + n\sqrt{\log C}\big) \text{ when combined with a Fibonacci heap}

    The original radix heap uses buckets of differences, [ℓ+2i−1,ℓ+2i)[\ell + 2^{i-1}, \ell + 2^i), so when all keys lie within CC of the minimum it needs only O(log⁡C)O(\log C) buckets, and Dijkstra's algorithm with integer weights at most CC runs in:

Thorup (2004) went further: an integer priority queue with O(1)O(1) insert and decrease-key and O(log⁡log⁡n)O(\log\log n) delete, deterministic and in linear space, which gives Dijkstra's algorithm O(m+nlog⁡log⁡n)O(m + n\log\log n) time on directed graphs with integer weights. For undirected graphs with integer weights, Thorup (1999) solved single-source shortest paths in O(m)O(m) time by not visiting the vertices in distance order at all; see Dijkstra's Algorithm in Depth.

Priority queues are sorting, and the limits of predecessor search

The theorem transfers every sorting result to priority queues. Han's deterministic O(nlog⁡log⁡n)O(n\log\log n) integer sort (2004) gives O(log⁡log⁡n)O(\log\log n) per operation, and Han and Thorup's O(nlog⁡log⁡n)O(n\sqrt{\log\log n}) expected-time sort (2002) gives O(log⁡log⁡n)O(\sqrt{\log\log n}) expected; the lesson Integer Sorting on the Word RAM covers those algorithms.

Predecessor search, the query vEB trees answer, has lower bounds in the cell-probe model, which charges only for memory accesses and therefore covers every word-RAM data structure. With polynomial space, Beame and Fich (1999) showed that the optimal query time for nn keys is

Θ(min⁡{log⁡log⁡Ulog⁡log⁡log⁡U, log⁡nlog⁡log⁡n}).\Theta\Big(\min\Big\{\frac{\log\log U}{\log\log\log U},\ \sqrt{\frac{\log n}{\log\log n}}\Big\}\Big).

Pătraşcu and Thorup (2006) found the exact trade-off between space and time; one consequence is that with near-linear space and UU polynomial in nn, van Emde Boas's Θ(log⁡log⁡U)\Theta(\log\log U) cannot be beaten, while fusion trees, at O(log⁡wn)O(\log_w n), win when words are much longer than log⁡n\log n bits.

Key takeaways

  • On the word RAM, keys are ww-bit integers that can be split, shifted and used as indices, so the comparison lower bound for priority queues does not apply.
  • A van Emde Boas tree keeps its minimum aside and splits keys into high and low halves; every operation makes one real recursive call on a universe of size U\sqrt U, so insert, delete and successor take O(log⁡log⁡U)O(\log\log U) time.
  • Hash tables for the non-empty clusters bring its space to O(nlog⁡log⁡U)O(n\log\log U), and indirection with buckets of Θ(log⁡U)\Theta(\log U) keys to O(n)O(n), the idea behind y-fast tries.
  • Monotone queues, such as Dijkstra's with integer weights, admit radix heaps: O(m+nlog⁡C)O(m + n\log C) for Dijkstra's algorithm, and O(m+nlog⁡log⁡n)O(m + n\log\log n) with Thorup's integer priority queue.
  • Integer priority queues are exactly as hard as integer sorting (Thorup, 2007), and van Emde Boas's O(log⁡log⁡U)O(\log\log U) is optimal for predecessor search in near-linear space when UU is polynomial in nn (Pătraşcu & Thorup, 2006).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does a successor query in a van Emde Boas tree take O(log⁡log⁡U)O(\log\log U) time rather than O(log⁡U)O(\log U)?

  1. It binary-searches the stored keys
  2. Each call recurses into a single structure over U\sqrt U values, so the number of key bits halves at every level
  3. It hashes the query key straight to its successor
  4. It keeps the keys in a sorted array and jumps by powers of two
Show the answer

B. Each call recurses into a single structure over U\sqrt U values, so the number of key bits halves at every level

The stored minimum and maximum let each call decide in O(1)O(1) which single substructure to enter: xx's cluster or the summary. So T(U)=T(U)+O(1)T(U) = T(\sqrt U) + O(1), and w=log⁡2Uw = \log_2 U bits can be halved only log⁡2w\log_2 w times.

Question 2

A vEB tree that keeps an array of U\sqrt U cluster pointers in every structure uses Θ(U)\Theta(U) space. How do you get down to O(n)O(n)?

  1. Store only the non-empty clusters in hash tables, then keep only one representative per bucket of Θ(log⁡U)\Theta(\log U) consecutive keys in the tree
  2. Use a smaller word size
  3. Store the summary only, without clusters
  4. It cannot be done: Θ(U)\Theta(U) space is inherent to the structure
Show the answer

A. Store only the non-empty clusters in hash tables, then keep only one representative per bucket of Θ(log⁡U)\Theta(\log U) consecutive keys in the tree

Hashing the clusters leaves at most one new structure per level for each insertion, O(nlog⁡log⁡U)O(n\log\log U) space. Indirection then stores only n/log⁡Un/\log U representatives in the tree and keeps each bucket in a small balanced tree, giving O(n)O(n) space with the same O(log⁡log⁡U)O(\log\log U) time, now expected and amortized because of hashing and bucket splits: the idea of Willard's y-fast trie (1983).

Question 3

A radix heap places each key in the bucket given by the highest bit in which it differs from the last extracted key. Why can it serve Dijkstra's algorithm but not a general priority queue?

  1. It needs keys smaller than 64
  2. It requires every inserted key to be at least the last extracted key, and Dijkstra's algorithm only inserts dist[u]+w(u,v)≥dist[u]\mathrm{dist}[u] + w(u, v) \ge \mathrm{dist}[u]
  3. It cannot hold two equal keys
  4. It works only on undirected graphs
Show the answer

B. It requires every inserted key to be at least the last extracted key, and Dijkstra's algorithm only inserts dist[u]+w(u,v)≥dist[u]\mathrm{dist}[u] + w(u, v) \ge \mathrm{dist}[u]

Buckets are defined relative to the last extracted key. A key smaller than that could not be placed correctly, and the argument that keys only move to lower buckets would fail. Dijkstra's queue is monotone because weights are non-negative.

Question 4

Thorup (2007) proved that on the word RAM, priority queues and sorting are equivalent: sorting nn keys in n⋅S(n)n\cdot S(n) time yields a priority queue with O(S(n))O(S(n)) time per operation, and conversely. What follows?

  1. Comparison-based heaps can beat log⁡n\log n per operation
  2. Van Emde Boas trees are optimal for every word size
  3. Integer sorting in O(n)O(n) time is impossible
  4. An O(n)O(n)-time integer sorting algorithm would give integer priority queues with O(1)O(1) time per operation, so both questions are the same open problem
Show the answer

D. An O(n)O(n)-time integer sorting algorithm would give integer priority queues with O(1)O(1) time per operation, so both questions are the same open problem

The reduction transfers every sorting bound: Han's deterministic O(nlog⁡log⁡n)O(n\log\log n) sort gives O(log⁡log⁡n)O(\log\log n) per operation, and Han and Thorup's expected O(nlog⁡log⁡n)O(n\sqrt{\log\log n}) sort gives O(log⁡log⁡n)O(\sqrt{\log\log n}) expected. Whether integers can be sorted in linear time, and hence whether constant-time integer priority queues exist, is open.

Further reading

  • P. van Emde Boas, "Preserving order in a forest in less than logarithmic time," Proceedings of the 16th IEEE Symposium on Foundations of Computer Science (1975), 75–84.
  • R. K. Ahuja, K. Mehlhorn, J. B. Orlin & R. E. Tarjan, "Faster algorithms for the shortest path problem," Journal of the ACM 37(2) (1990), 213–223.
  • M. Thorup, "Equivalence between priority queues and sorting," Journal of the ACM 54(6) (2007), article 28.
  • M. Pătraşcu & M. Thorup, "Time-space trade-offs for predecessor search," Proceedings of the 38th ACM Symposium on Theory of Computing (STOC) (2006).
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 3rd ed. (MIT Press, 2009), chapter 20.