TExcelTAD

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 O(lg⁡w)O(\lg w) expected time, updates O(w)O(w), and the space is O(nw)O(n w). 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 ww over the universe {0,…,2w−1}\{0, \ldots, 2^w - 1\}: the root is the empty prefix, the children of a prefix pp are p0p0 and p1p1, and the leaves are the keys. Keep only the nodes that are prefixes of some stored key. That trie has at most nw+1n w + 1 nodes, and storing it as pointers would give O(w)O(w) search time by walking down. The x-fast trie instead stores, for each level ℓ=0,…,w\ell = 0, \ldots, w, a hash table TℓT_\ell of all ℓ\ell-bit prefixes of stored keys.

The key fact: for a query xx, the predicate "the top ℓ\ell bits of xx are in TℓT_\ell" is monotone in ℓ\ell. If a stored key shares ℓ\ell bits with xx, it shares every shorter prefix too. So the longest common prefix of xx with any stored key can be found by binary search over ℓ∈{0,…,w}\ell \in \{0, \ldots, w\}, using O(lg⁡w)O(\lg w) hash lookups.

From the longest prefix to the successor

Let pp be the longest prefix of xx in the trie, at level ℓ<w\ell < w, and let bb be bit ℓ\ell of xx (the next bit after the prefix). The node pp exists but its child pbpb does not, so pp has only the other child.

  • If b=0b = 0, every key below pp starts with p1p1 and is larger than xx: the successor of xx is the minimum key below pp.
  • If b=1b = 1, every key below pp starts with p0p0 and is smaller than xx: the predecessor of xx is the maximum key below pp.

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 O(1)O(1). If ℓ=w\ell = w, xx itself is stored and its successor is the next leaf.

text
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 predecessor

INSERT(x)(x) adds the w+1w + 1 prefixes of xx to their tables, updates the min and max of each, and splices xx into the linked list next to its predecessor or successor (found by a query first). That is O(w)O(w) expected time. DELETE is the reverse, also O(w)O(w): 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 w=4w = 4 and the keys 2,5,6,132, 5, 6, 13 (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.

python · try it yourself
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 x=0111x = 0111 the search stops at prefix 011011 and the next bit is 1: the subtree below 011011 holds only smaller keys, so the predecessor is its maximum, 6, and the successor is the next key in the list, 13. For x=1100x = 1100 the next bit is 0: the successor is the minimum below 110110, 13. For x=0000x = 0000 the search stops at 0000 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.

python · try it yourself
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 ⌈lg⁡33⌉=6\lceil \lg 33 \rceil = 6 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 Θ(nw)\Theta(n w) in general: the top lg⁡n\lg n levels are shared, the remaining w−lg⁡nw - \lg n 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.

cpp · try it yourself
#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 O(1)O(1) and not O(lg⁡n)O(\lg n).

The bounds

Operation Time Why
SUCCESSOR, PREDECESSOR, MEMBER O(lg⁡w)O(\lg w) expected binary search over w+1w + 1 levels, one hash lookup each, plus O(1)O(1) list steps
INSERT, DELETE O(w)O(w) expected every one of the w+1w + 1 prefixes changes
space O(nw)O(n w) words up to w+1w + 1 prefixes per key

"Expected" comes from hashing. With a dynamic perfect hashing scheme the lookups are O(1)O(1) worst case and the queries O(lg⁡w)O(\lg w) worst case, while updates stay randomized and amortized.

Why the binary search is correct (proof sketch)

Let P(ℓ)P(\ell) be "the ℓ\ell-bit prefix of xx is a prefix of some stored key". P(0)P(0) is true whenever the set is non-empty, and if P(ℓ)P(\ell) holds then P(ℓ′)P(\ell') holds for every ℓ′<ℓ\ell' < \ell (a prefix of a prefix). So PP is true on 0,…,L0, \ldots, L and false above, and the loop keeps the invariant "P(lo)P(lo) is true and P(ℓ)P(\ell) is false for every ℓ>hi\ell > hi". Each iteration shrinks hi−lohi - lo by about half, and at the end lo=hi=Llo = hi = L, the longest common prefix length.

For the successor: at level L<wL < w the node pp exists and pbpb does not, where bb is the next bit of xx. If b=0b = 0, every key in pp's subtree begins with p1>p0p1 > p0, so all of them exceed xx, and no key outside the subtree lies between xx and them (keys outside differ from xx within the first LL bits, so they are smaller than everything starting with pp or larger than everything starting with pp). Hence the minimum of the subtree is the successor. The case b=1b = 1 is symmetric.

Test yourself

Why can the longest common prefix of xx with the stored keys be found by binary search on the prefix length?

  1. The hash tables are sorted
  2. Whether the ℓ\ell-bit prefix of xx is stored is monotone in ℓ\ell: true up to some length and false after it
  3. Keys are random
  4. The trie is balanced

The longest prefix pp of xx is found at level ℓ\ell, and bit ℓ\ell of xx is 1. What does the minimum and maximum information at pp give directly?

  1. The successor: the minimum below pp
  2. The predecessor: the maximum below pp, since all keys below pp start with p0p0 and are smaller than xx
  3. Nothing; the search must continue
  4. The key xx itself

Which bound of the x-fast trie does the y-fast trie improve?

  1. Query time O(lg⁡w)O(\lg w)
  2. Space O(nw)O(nw) and update time O(w)O(w)
  3. The need for hashing
  4. The word size