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 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, clusters, a summary) and prove time for insert, successor and delete from .
- Reduce its space from to with hashing, and to 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 -bit integers from the universe , , with , and arithmetic, shifts and bitwise operations on whole words take time. An algorithm may also use a key as an array index. The lower bound "insert plus extract-min costs 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 , and in a monotone queue, where extracted keys never decrease, extract-min scans forward from the last minimum. When all keys lie within of the current minimum, as in Dijkstra's algorithm with integer weights at most , a cyclic array of buckets suffices and the whole run costs .
| Structure | Operations | Time per operation | Space |
|---|---|---|---|
| Bucket queue (Dial, 1969) | monotone insert, extract-min | insert; scans for the minimum | |
| van Emde Boas tree (1975) | insert, delete, min, successor, predecessor | worst case | ; with hashing and indirection |
| Radix heap (Ahuja, Mehlhorn, Orlin & Tarjan, 1990) | monotone insert, decrease-key, extract-min | amortized extract-min | |
| Fusion tree (Fredman & Willard, 1993) | insert, delete, predecessor | ||
| Thorup (2004) | insert, decrease-key, delete | , , , deterministic |
van Emde Boas trees
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].minClusters 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).
Successor. If is below the minimum, answer at once. Otherwise the cluster's stored maximum says in whether the answer lies in '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 :
Insert. Because the minimum is kept outside the clusters, an empty structure takes its first key in . So when '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.
Solve it in terms of the word size: , so with each call halves the number of bits.
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 . As a priority queue, find-min is and extract-min and decrease-key cost ; duplicate keys need a count per key.
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
: six halvings, since . 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 at all, only on the word size.
From Θ(U) space to O(n)
The textbook vEB tree stores an array of cluster pointers in every structure, so its space satisfies . That is fine for and absurd for .
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 levels, so keys occupy space; operations now run in expected time, or worst case with dynamic perfect hashing at the price of amortization.
Indirection. Sort the keys into buckets of 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 keys and takes space, a query costs in the tree plus inside one bucket, and splitting or merging a bucket happens rarely enough to cost 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 space for van Emde Boas's structure itself.
In insert, what makes it possible to recurse into only one substructure at each level?
- The summary is always empty when a cluster is non-empty
- An empty structure takes its first key as its stored minimum in , without recursing, so a key landing in an empty cluster costs one recursive call into the summary, and otherwise the summary needs no change
- Clusters are stored in a hash table, which inserts in
- 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 , 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 would give instead of .
Monotone queues: radix heaps for Dijkstra
Dijkstra's priority queue is monotone: the extracted keys never decrease, and every inserted key, , 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 when the highest bit in which it differs from the last extracted key is bit , and in bucket 0 when it equals that key.
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 lastA key enters one bucket and can only move down, so its total movement is . For Dijkstra's algorithm, push pairs (key, vertex) keyed on the distance, and skip stale entries as with any lazy-deletion heap.
A key in bucket agrees with , the last extracted key, on every bit above bit , and has bit set where has it clear, because . The new reference point , the bucket's minimum, has the same two properties, so and agree on every bit from upward:
So each redistribution sends every key of bucket to a strictly lower bucket, and a key moves at most times before it reaches bucket 0. Charging the moves to the key's insertion:
The original radix heap uses buckets of differences, , so when all keys lie within of the minimum it needs only buckets, and Dijkstra's algorithm with integer weights at most runs in:
Thorup (2004) went further: an integer priority queue with insert and decrease-key and delete, deterministic and in linear space, which gives Dijkstra's algorithm time on directed graphs with integer weights. For undirected graphs with integer weights, Thorup (1999) solved single-source shortest paths in 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 integer sort (2004) gives per operation, and Han and Thorup's expected-time sort (2002) gives 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 keys is
Pătraşcu and Thorup (2006) found the exact trade-off between space and time; one consequence is that with near-linear space and polynomial in , van Emde Boas's cannot be beaten, while fusion trees, at , win when words are much longer than bits.
Key takeaways
- On the word RAM, keys are -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 , so insert, delete and successor take time.
- Hash tables for the non-empty clusters bring its space to , and indirection with buckets of keys to , the idea behind y-fast tries.
- Monotone queues, such as Dijkstra's with integer weights, admit radix heaps: for Dijkstra's algorithm, and with Thorup's integer priority queue.
- Integer priority queues are exactly as hard as integer sorting (Thorup, 2007), and van Emde Boas's is optimal for predecessor search in near-linear space when is polynomial in (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.
Why does a successor query in a van Emde Boas tree take time rather than ?
- It binary-searches the stored keys
- Each call recurses into a single structure over values, so the number of key bits halves at every level
- It hashes the query key straight to its successor
- 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 values, so the number of key bits halves at every level
The stored minimum and maximum let each call decide in which single substructure to enter: 's cluster or the summary. So , and bits can be halved only times.
A vEB tree that keeps an array of cluster pointers in every structure uses space. How do you get down to ?
- Store only the non-empty clusters in hash tables, then keep only one representative per bucket of consecutive keys in the tree
- Use a smaller word size
- Store the summary only, without clusters
- It cannot be done: 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 consecutive keys in the tree
Hashing the clusters leaves at most one new structure per level for each insertion, space. Indirection then stores only representatives in the tree and keeps each bucket in a small balanced tree, giving space with the same time, now expected and amortized because of hashing and bucket splits: the idea of Willard's y-fast trie (1983).
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?
- It needs keys smaller than 64
- It requires every inserted key to be at least the last extracted key, and Dijkstra's algorithm only inserts
- It cannot hold two equal keys
- 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
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.
Thorup (2007) proved that on the word RAM, priority queues and sorting are equivalent: sorting keys in time yields a priority queue with time per operation, and conversely. What follows?
- Comparison-based heaps can beat per operation
- Van Emde Boas trees are optimal for every word size
- Integer sorting in time is impossible
- An -time integer sorting algorithm would give integer priority queues with time per operation, so both questions are the same open problem
Show the answer
D. An -time integer sorting algorithm would give integer priority queues with time per operation, so both questions are the same open problem
The reduction transfers every sorting bound: Han's deterministic sort gives per operation, and Han and Thorup's expected sort gives 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.