X-Fast Tries
The van Emde Boas tree halves the key length at each level of recursion. The x-fast trie (Willard, 1983) does the same thing with hashing in a single, flat structure: it stores every prefix of every key in hash tables, then binary searches over the prefix length. Queries take expected time, updates , and the space is . It is the first half of the y-fast trie, which fixes the space and the update time.
The trie and its prefixes
Picture a binary trie of depth over the universe : the root is the empty prefix, the children of a prefix are and , and the leaves are the keys. Keep only the nodes that are prefixes of some stored key. That trie has at most nodes, and storing it as pointers would give search time by walking down. The x-fast trie instead stores, for each level , a hash table of all -bit prefixes of stored keys.
The key fact: for a query , the predicate "the top bits of are in " is monotone in . If a stored key shares bits with , it shares every shorter prefix too. So the longest common prefix of with any stored key can be found by binary search over , using hash lookups.
From the longest prefix to the successor
Let be the longest prefix of in the trie, at level , and let be bit of (the next bit after the prefix). The node exists but its child does not, so has only the other child.
- If , every key below starts with and is larger than : the successor of is the minimum key below .
- If , every key below starts with and is smaller than : the predecessor of is the maximum key below .
So each trie node stores the minimum and maximum key in its subtree (the classic description stores a single "descendant pointer" to the relevant one; the information is the same). The stored keys are also linked in sorted order in a doubly linked list, which turns a predecessor into a successor in . If , itself is stored and its successor is the next leaf.
SUCCESSOR(x)
1 lo, hi = 0, w // invariant: prefix(x, lo) is in T[lo]; nothing longer than hi is
2 while lo < hi
3 mid = ceil((lo + hi) / 2)
4 if prefix(x, mid) in T[mid] lo = mid else hi = mid - 1
5 node = T[lo][prefix(x, lo)]
6 if lo == w return next(x) // x is stored
7 if bit lo of x == 0 return node.min // only the 1-child exists: all keys there are > x
8 else return next(node.max) // only the 0-child exists: node.max is the predecessorINSERT adds the prefixes of to their tables, updates the min and max of each, and splices into the linked list next to its predecessor or successor (found by a query first). That is expected time. DELETE is the reverse, also : walking up, a prefix whose subtree becomes empty is removed, and the others get new min or max values from their remaining child.
A small trace
With and the keys (binary 0010, 0101, 0110, 1101), the program prints the five prefix tables and traces the binary search for three queries, with the minimum and maximum stored at the node where each search stops.
w = 4
keys = [2, 5, 6, 13] # 0010, 0101, 0110, 1101
T = [dict() for _ in range(w + 1)]
for x in keys:
for l in range(w + 1):
p = x >> (w - l)
lo, hi = T[l].get(p, (x, x))
T[l][p] = (min(lo, x), max(hi, x))
for l in range(w + 1):
level = ", ".join(f"{p:0{l}b}" if l else "(root)" for p in sorted(T[l]))
print(f"T[{l}]: {level}")
def trace(x):
lo, hi, steps = 0, w, []
while lo < hi:
mid = (lo + hi + 1) // 2
p = x >> (w - mid)
hit = p in T[mid]
steps.append(f"{p:0{mid}b}? {'yes' if hit else 'no'}")
lo, hi = (mid, hi) if hit else (lo, mid - 1)
return lo, steps
for x in [7, 12, 0]:
l, steps = trace(x)
mn, mx = T[l][x >> (w - l)]
nxt = (x >> (w - l - 1)) & 1 if l < w else None
print(f"x = {x:04b}: " + "; ".join(steps) + f" -> longest prefix {l} bits, next bit {nxt}, "
f"subtree min {mn} max {mx}")T[0]: (root)
T[1]: 0, 1
T[2]: 00, 01, 11
T[3]: 001, 010, 011, 110
T[4]: 0010, 0101, 0110, 1101
x = 0111: 01? yes; 011? yes; 0111? no -> longest prefix 3 bits, next bit 1, subtree min 6 max 6
x = 1100: 11? yes; 110? yes; 1100? no -> longest prefix 3 bits, next bit 0, subtree min 13 max 13
x = 0000: 00? yes; 000? no -> longest prefix 2 bits, next bit 0, subtree min 2 max 2
For the search stops at prefix and the next bit is 1: the subtree below holds only smaller keys, so the predecessor is its maximum, 6, and the successor is the next key in the list, 13. For the next bit is 0: the successor is the minimum below , 13. For the search stops at and the successor is 2.
An implementation
The program keeps the tables as Python dictionaries from prefix to [min, max], counts hash lookups per query, and checks 3000 random successor and predecessor queries against binary search.
import bisect, random
class XFastTrie:
def __init__(self, w):
self.w = w
self.T = [dict() for _ in range(w + 1)] # T[l]: l-bit prefix -> [min, max] of its subtree
self.next, self.prev = {}, {} # sorted doubly linked list of keys
self.lookups = 0
def _lcp(self, x):
lo, hi = 0, self.w
while lo < hi:
mid = (lo + hi + 1) // 2
self.lookups += 1
if (x >> (self.w - mid)) in self.T[mid]: lo = mid
else: hi = mid - 1
return lo
def successor(self, x): # smallest key > x
if not self.T[0]: return None
l = self._lcp(x)
if l == self.w: return self.next.get(x)
lo_key, hi_key = self.T[l][x >> (self.w - l)]
if (x >> (self.w - l - 1)) & 1 == 0: return lo_key
return self.next.get(hi_key)
def predecessor(self, x): # largest key < x
if not self.T[0]: return None
l = self._lcp(x)
if l == self.w: return self.prev.get(x)
lo_key, hi_key = self.T[l][x >> (self.w - l)]
if (x >> (self.w - l - 1)) & 1 == 1: return hi_key
return self.prev.get(lo_key)
def insert(self, x): # O(w) expected
if x in self.T[self.w]: return
s, p = self.successor(x), self.predecessor(x)
for l in range(self.w + 1):
key = x >> (self.w - l)
mm = self.T[l].get(key)
if mm is None: self.T[l][key] = [x, x]
else: mm[0], mm[1] = min(mm[0], x), max(mm[1], x)
if p is not None: self.next[p] = x; self.prev[x] = p
if s is not None: self.prev[s] = x; self.next[x] = s
rng = random.Random(1983)
w = 32
t, keys = XFastTrie(w), set()
while len(keys) < 3000:
keys.add(rng.randrange(1 << w))
for k in sorted(keys, key=lambda k: (k * 2654435761) % (1 << 32)): # a scrambled insertion order
t.insert(k)
srt = sorted(keys)
t.lookups, worst = 0, 0
for _ in range(3000):
q = rng.randrange(1 << w)
before = t.lookups
i = bisect.bisect_right(srt, q)
assert t.successor(q) == (srt[i] if i < len(srt) else None)
j = bisect.bisect_left(srt, q)
assert t.predecessor(q) == (srt[j - 1] if j else None)
worst = max(worst, t.lookups - before)
nodes = sum(len(T) for T in t.T)
print(f"n = {len(keys)}, w = {w}: trie nodes stored {nodes} ({nodes / len(keys):.1f} per key, at most w + 1 = {w + 1})")
print(f"hash lookups per successor + predecessor pair: average {t.lookups / 3000:.2f}, worst {worst}")n = 3000, w = 32: trie nodes stored 64606 (21.5 per key, at most w + 1 = 33)
hash lookups per successor + predecessor pair: average 10.00, worst 10
Each query is a binary search over 33 prefix lengths, at most lookups, here 5 per query. Shared prefixes near the root bring the space down to about 21 nodes per key instead of 33, but it is still in general: the top levels are shared, the remaining are not.
In C++
A compact version with std::unordered_map per level and the same query logic. It prints the successor and predecessor of a few queries over a small set of 8-bit keys, so the trie levels can be followed by hand.
#include <cstdint>
#include <cstdio>
#include <map>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
class XFastTrie {
int w;
std::vector<std::unordered_map<std::uint64_t, std::pair<std::uint64_t, std::uint64_t>>> T; // prefix -> (min, max)
std::map<std::uint64_t, int> leaves; // stands in for the doubly linked list of keys
int lcp(std::uint64_t x) const {
int lo = 0, hi = w;
while (lo < hi) {
int mid = (lo + hi + 1) / 2;
if (T[mid].count(x >> (w - mid))) lo = mid; else hi = mid - 1;
}
return lo;
}
std::optional<std::uint64_t> next_leaf(std::uint64_t k) const {
auto it = leaves.upper_bound(k);
return it == leaves.end() ? std::nullopt : std::optional(it->first);
}
std::optional<std::uint64_t> prev_leaf(std::uint64_t k) const {
auto it = leaves.lower_bound(k);
return it == leaves.begin() ? std::nullopt : std::optional(std::prev(it)->first);
}
public:
explicit XFastTrie(int bits) : w(bits), T(bits + 1) {}
void insert(std::uint64_t x) {
for (int l = 0; l <= w; ++l) {
auto [it, fresh] = T[l].try_emplace(x >> (w - l), x, x);
if (!fresh) { it->second.first = std::min(it->second.first, x); it->second.second = std::max(it->second.second, x); }
}
leaves[x] = 1;
}
std::optional<std::uint64_t> successor(std::uint64_t x) const {
if (T[0].empty()) return std::nullopt;
int l = lcp(x);
if (l == w) return next_leaf(x);
auto [mn, mx] = T[l].at(x >> (w - l));
if (((x >> (w - l - 1)) & 1) == 0) return mn;
return next_leaf(mx);
}
std::optional<std::uint64_t> predecessor(std::uint64_t x) const {
if (T[0].empty()) return std::nullopt;
int l = lcp(x);
if (l == w) return prev_leaf(x);
auto [mn, mx] = T[l].at(x >> (w - l));
if (((x >> (w - l - 1)) & 1) == 1) return mx;
return prev_leaf(mn);
}
int longest_prefix(std::uint64_t x) const { return lcp(x); }
};
int main() {
XFastTrie t(8);
for (std::uint64_t k : {17, 23, 64, 100, 101, 200, 250}) t.insert(k);
for (std::uint64_t q : {0, 20, 64, 102, 199, 255}) {
auto s = t.successor(q), p = t.predecessor(q);
std::printf("x = %3llu: longest prefix %d bits, predecessor %4s, successor %4s\n",
static_cast<unsigned long long>(q), t.longest_prefix(q),
p ? std::to_string(*p).c_str() : "-", s ? std::to_string(*s).c_str() : "-");
}
}x = 0: longest prefix 3 bits, predecessor -, successor 17
x = 20: longest prefix 6 bits, predecessor 17, successor 23
x = 64: longest prefix 8 bits, predecessor 23, successor 100
x = 102: longest prefix 6 bits, predecessor 101, successor 200
x = 199: longest prefix 4 bits, predecessor 101, successor 200
x = 255: longest prefix 5 bits, predecessor 250, successor -
The C++ version uses std::map for the leaf list to stay short; a real x-fast trie keeps explicit prev and next pointers so that this step is and not .
The bounds
| Operation | Time | Why |
|---|---|---|
| SUCCESSOR, PREDECESSOR, MEMBER | expected | binary search over levels, one hash lookup each, plus list steps |
| INSERT, DELETE | expected | every one of the prefixes changes |
| space | words | up to prefixes per key |
"Expected" comes from hashing. With a dynamic perfect hashing scheme the lookups are worst case and the queries worst case, while updates stay randomized and amortized.
Why the binary search is correct (proof sketch)
Let be "the -bit prefix of is a prefix of some stored key". is true whenever the set is non-empty, and if holds then holds for every (a prefix of a prefix). So is true on and false above, and the loop keeps the invariant " is true and is false for every ". Each iteration shrinks by about half, and at the end , the longest common prefix length.
For the successor: at level the node exists and does not, where is the next bit of . If , every key in 's subtree begins with , so all of them exceed , and no key outside the subtree lies between and them (keys outside differ from within the first bits, so they are smaller than everything starting with or larger than everything starting with ). Hence the minimum of the subtree is the successor. The case is symmetric.
Test yourself
Why can the longest common prefix of with the stored keys be found by binary search on the prefix length?
- The hash tables are sorted
- Whether the -bit prefix of is stored is monotone in : true up to some length and false after it
- Keys are random
- The trie is balanced
The longest prefix of is found at level , and bit of is 1. What does the minimum and maximum information at give directly?
- The successor: the minimum below
- The predecessor: the maximum below , since all keys below start with and are smaller than
- Nothing; the search must continue
- The key itself
Which bound of the x-fast trie does the y-fast trie improve?
- Query time
- Space and update time
- The need for hashing
- The word size