TExcelTAD
Home › Advanced & Succinct Data Structures › Y-Fast Tries and Indirection

Y-Fast Tries and Indirection

The x-fast trie answers successor queries in O(lg⁡w)O(\lg w) expected time, but it stores w+1w + 1 prefixes per key and rewrites all of them on every update. The y-fast trie (Willard, 1983) removes both costs with indirection: only one key in about ww goes into the x-fast trie, and the rest wait in small balanced trees below it.

Theorem (Willard). A y-fast trie stores nn keys from {0,…,2w−1}\{0, \ldots, 2^w - 1\} in O(n)O(n) words. SUCCESSOR, PREDECESSOR and MEMBER take O(lg⁡w)O(\lg w) expected time; INSERT and DELETE take O(lg⁡w)O(\lg w) expected amortized time.

Since lg⁡w=lg⁡lg⁡U\lg w = \lg \lg U, these are the bounds of a space-reduced van Emde Boas tree, reached with a simpler structure.

The structure

  1. Partition the sorted keys into consecutive buckets of between w/2w/2 and 2w2w keys each (a single bucket may be smaller when n<w/2n < w/2).
  2. Each bucket is a balanced BST (a red-black tree) of at most 2w2w keys, so searching, inserting and deleting inside it cost O(lg⁡w)O(\lg w).
  3. Each bucket has a representative rr, and the bucket holds exactly the keys in [r,r′)[r, r'), where r′r' is the next representative. The representatives are stored in an x-fast trie. The first representative is 00, so every key has a bucket.

A representative is a separator, not necessarily a stored key: deleting the key equal to rr leaves rr in place. Representatives change only when buckets split or merge.

Operations

  • SUCCESSOR(x)(x). Find xx's bucket: the largest representative r≤xr \le x, which is a predecessor query in the x-fast trie, O(lg⁡w)O(\lg w) expected. Search the bucket's BST for the smallest key above xx, O(lg⁡w)O(\lg w). If there is none, the answer is the minimum of the next bucket, reached through the x-fast trie's linked list.
  • INSERT(x)(x). Find the bucket and insert into its BST, O(lg⁡w)O(\lg w). If the bucket now has more than 2w2w keys, split it at its median: the upper half becomes a new bucket whose representative is its smallest key, inserted into the x-fast trie at cost O(w)O(w).
  • DELETE(x)(x). Find the bucket and delete from its BST. If it drops below w/2w/2 keys, merge it with a neighbour (removing one representative, O(w)O(w)), and if the merged bucket has more than 3w/23w/2 keys, split it again.

Why the amortized update cost is O(lg⁡w)O(\lg w)

Every bucket that a split or merge creates has a size safely between the thresholds. A split of a bucket with 2w+12w + 1 keys gives two buckets of about ww keys. A merge combines a bucket of w/2−1w/2 - 1 keys with a neighbour of between w/2w/2 and 2w2w, giving between w−1w - 1 and 3w−13w - 1 keys; if that is more than 3w/23w/2, it is split again into two halves of at least 3w/43w/4. So every new bucket has between about 3w/43w/4 and 3w/23w/2 keys, at least w/4w/4 away from both w/2w/2 and 2w2w. Before it splits or merges again, Ω(w)\Omega(w) inserts or deletes must land in it. Charging the O(w)O(w) x-fast trie update to those Ω(w)\Omega(w) operations gives O(1)O(1) amortized per update for the top level, on top of the O(lg⁡w)O(\lg w) BST work.

Space. The buckets hold nn keys in O(n)O(n) words. There are O(n/w)O(n / w) representatives, each using O(w)O(w) words in the x-fast trie, which is O(n)O(n) as well.

The program counts the entries an x-fast trie needs for nn random 64-bit keys, and the entries of a y-fast trie: an x-fast trie over one representative per ww keys, plus one entry per key in the buckets.

python · try it yourself
import random

def prefix_entries(keys, w):                     # entries of an x-fast trie storing these keys
    return sum(len({k >> (w - l) for k in keys}) for l in range(w + 1))

rng = random.Random(64)
w = 64
for n in [1000, 5000, 20000]:
    keys = sorted({rng.getrandbits(w) for _ in range(n)})
    reps = keys[::w]                             # one representative per bucket of w keys
    x = prefix_entries(keys, w)
    y = prefix_entries(reps, w) + len(keys)      # x-fast trie on representatives + the keys in buckets
    print(f"n = {n:5}: x-fast trie {x:8} entries ({x / n:4.1f} per key); "
          f"y-fast trie {y:6} ({y / n:4.2f} per key, {len(reps)} representatives)")
n =  1000: x-fast trie    55149 entries (55.1 per key); y-fast trie   1991 (1.99 per key, 16 representatives)
n =  5000: x-fast trie   264040 entries (52.8 per key); y-fast trie   9709 (1.94 per key, 79 representatives)
n = 20000: x-fast trie  1016565 entries (50.8 per key); y-fast trie  38039 (1.90 per key, 313 representatives)

About 50 prefix entries per key for the x-fast trie, a little under 2 for the y-fast trie, whatever nn is.

An implementation

The program below builds the whole structure: an x-fast trie with deletion (walking up from the leaf and refreshing each prefix's minimum and maximum from its children) and buckets kept as sorted Python lists. A sorted list stands in for the BST: bisect does the O(lg⁡w)O(\lg w) search, though inserting into a list shifts up to 2w2w entries, which a real BST would avoid. The run grows the set, churns it with mixed updates, then shrinks it, checking bucket sizes and 500 successor queries after each phase. The last column is the number of x-fast trie prefix entries written per update.

python · try it yourself
import bisect, random

class XFast:
    """x-fast trie over w-bit keys: T[l] maps an l-bit prefix to [min, max]; keys in a linked list."""
    def __init__(self, w):
        self.w, self.T = w, [dict() for _ in range(w + 1)]
        self.next, self.prev = {}, {}
        self.lookups = self.writes = 0
    def _locate(self, x):                            # (pred, succ) of x among keys != x
        if not self.T[0]: return None, None
        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
        if lo == self.w: return self.prev.get(x), self.next.get(x)
        mn, mx = self.T[lo][x >> (self.w - lo)]
        if (x >> (self.w - lo - 1)) & 1: return mx, self.next.get(mx)
        return self.prev.get(mn), mn
    def floor(self, x):                              # largest key <= x
        return x if x in self.T[self.w] else self._locate(x)[0]
    def successor(self, x):                          # smallest key > x
        return self._locate(x)[1]
    def insert(self, x):
        p, s = self._locate(x)
        for l in range(self.w + 1):
            self.writes += 1
            k = x >> (self.w - l)
            mm = self.T[l].get(k)
            if mm is None: self.T[l][k] = [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
    def delete(self, x):
        p, s = self.prev.pop(x, None), self.next.pop(x, None)
        if p is not None:
            if s is not None: self.next[p] = s
            else: del self.next[p]
        if s is not None:
            if p is not None: self.prev[s] = p
            else: del self.prev[s]
        del self.T[self.w][x]
        for l in range(self.w - 1, -1, -1):          # walk up: drop empty prefixes, refresh min/max
            self.writes += 1
            k = x >> (self.w - l)
            kids = [c for c in (self.T[l + 1].get(2 * k), self.T[l + 1].get(2 * k + 1)) if c is not None]
            if not kids: del self.T[l][k]
            else: self.T[l][k] = [kids[0][0], kids[-1][1]]

class YFast:
    def __init__(self, w):
        self.w, self.top = w, XFast(w)
        self.buckets = {0: []}                       # representative -> sorted bucket; rep 0 is never removed
        self.top.insert(0)
        self.lo, self.hi = w // 2, 2 * w
    def _bucket(self, x):
        r = self.top.floor(x)
        return r, self.buckets[r]
    def successor(self, x):
        r, b = self._bucket(x)
        i = bisect.bisect_right(b, x)                # O(lg w) in a balanced BST of <= 2w keys
        if i < len(b): return b[i]
        s = self.top.successor(r)
        return None if s is None else self.buckets[s][0]
    def insert(self, x):
        r, b = self._bucket(x)
        i = bisect.bisect_left(b, x)
        if i < len(b) and b[i] == x: return
        b.insert(i, x)
        if len(b) > self.hi:                         # split: the upper half gets a new representative
            m = len(b) // 2
            new = b[m]
            self.buckets[r], self.buckets[new] = b[:m], b[m:]
            self.top.insert(new)
    def delete(self, x):
        r, b = self._bucket(x)
        b.remove(x)
        if len(b) >= self.lo or len(self.buckets) == 1: return
        s = self.top.successor(r)
        if s is None:                                # last bucket: merge into its left neighbour
            s, r = r, self.top.floor(r - 1)
        merged = self.buckets[r] + self.buckets.pop(s)
        self.top.delete(s)
        self.buckets[r] = merged
        if len(merged) > 3 * self.w // 2:            # split again, far from both thresholds
            m = len(merged) // 2
            self.buckets[r], self.buckets[merged[m]] = merged[:m], merged[m:]
            self.top.insert(merged[m])

rng = random.Random(2003)
w = 32
y, ref = YFast(w), []
ops = 0
for phase, n_ops, p_insert in [("grow", 6000, 0.9), ("churn", 6000, 0.5), ("shrink", 5000, 0.1)]:
    y.top.lookups = y.top.writes = 0
    for _ in range(n_ops):
        if ref and rng.random() >= p_insert:
            x = ref.pop(rng.randrange(len(ref)))
            y.delete(x)
        else:
            x = rng.randrange(1, 1 << w)
            if x in y.buckets.get(y.top.floor(x), []): continue
            y.insert(x); bisect.insort(ref, x)
    # check every bucket size and 500 successor queries
    ref.sort()
    sizes = [len(b) for b in y.buckets.values()]
    for _ in range(500):
        q = rng.randrange(1 << w)
        i = bisect.bisect_right(ref, q)
        assert y.successor(q) == (ref[i] if i < len(ref) else None)
    print(f"{phase:6}: n = {len(ref):5}, buckets {len(sizes):3}, sizes {min(sizes)}..{max(sizes)}, "
          f"x-fast prefix writes per update {y.top.writes / n_ops:.2f} (w + 1 = {w + 1})")
grow  : n =  4876, buckets 105, sizes 31..63, x-fast prefix writes per update 0.57 (w + 1 = 33)
churn : n =  4908, buckets 118, sizes 23..62, x-fast prefix writes per update 0.07 (w + 1 = 33)
shrink: n =   852, buckets  33, sizes 17..40, x-fast prefix writes per update 0.71 (w + 1 = 33)

Bucket sizes stay within [w/2,2w]=[16,64][w/2, 2w] = [16, 64] in every phase, and the x-fast trie, which would need w+1=33w + 1 = 33 prefix writes per update on its own, gets well under one per update on average. The churn phase barely touches it: with the set size stable, buckets rarely cross a threshold.

In C++

A growing y-fast trie with std::set buckets (red-black trees in practice) over an insert-only x-fast trie. It inserts 20000 random 32-bit keys, checks 5000 successor queries against a std::set of all keys, and reports how often the top level was written.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <iterator>
#include <map>
#include <optional>
#include <random>
#include <set>
#include <unordered_map>
#include <vector>

using u64 = std::uint64_t;

// Top level: an x-fast trie over the representatives (insert-only here, enough for a growing set).
class XFast {
    int w;
    std::vector<std::unordered_map<u64, std::pair<u64, u64>>> T;
    std::unordered_map<u64, u64> nxt, prv;
public:
    long writes = 0;
    explicit XFast(int bits) : w(bits), T(bits + 1) {}
    std::pair<std::optional<u64>, std::optional<u64>> locate(u64 x) const {   // neighbours of x
        if (T[0].empty()) return {};
        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;
        }
        auto get = [](const std::unordered_map<u64, u64>& m, u64 k) {
            auto it = m.find(k);
            return it == m.end() ? std::optional<u64>() : std::optional<u64>(it->second);
        };
        if (lo == w) return {get(prv, x), get(nxt, x)};
        auto [mn, mx] = T[lo].at(x >> (w - lo));
        if ((x >> (w - lo - 1)) & 1) return {mx, get(nxt, mx)};
        return {get(prv, mn), mn};
    }
    std::optional<u64> floor(u64 x) const { return T[w].count(x) ? std::optional<u64>(x) : locate(x).first; }
    std::optional<u64> successor(u64 x) const { return locate(x).second; }
    void insert(u64 x) {
        auto [p, s] = locate(x);
        for (int l = 0; l <= w; ++l) {
            ++writes;
            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); }
        }
        if (p) { nxt[*p] = x; prv[x] = *p; }
        if (s) { prv[*s] = x; nxt[x] = *s; }
    }
};

class YFast {
    int w;
    XFast top;
    std::map<u64, std::set<u64>> buckets;   // representative -> bucket (a balanced BST)
public:
    explicit YFast(int bits) : w(bits), top(bits) { buckets[0]; top.insert(0); }
    long top_writes() const { return top.writes; }
    std::size_t bucket_count() const { return buckets.size(); }
    void insert(u64 x) {
        u64 r = *top.floor(x);
        auto& b = buckets[r];
        b.insert(x);
        if (static_cast<int>(b.size()) > 2 * w) {             // split the bucket in two
            auto mid = std::next(b.begin(), b.size() / 2);
            u64 rep = *mid;
            buckets[rep] = std::set<u64>(mid, b.end());
            b.erase(mid, b.end());
            top.insert(rep);
        }
    }
    std::optional<u64> successor(u64 x) const {
        u64 r = *top.floor(x);
        const auto& b = buckets.at(r);
        if (auto it = b.upper_bound(x); it != b.end()) return *it;
        auto s = top.successor(r);
        if (!s) return std::nullopt;
        return *buckets.at(*s).begin();
    }
};

int main() {
    const int w = 32;
    std::mt19937_64 rng(1983);
    YFast y(w);
    std::set<u64> ref;
    for (int i = 0; i < 20000; ++i) {
        u64 x = 1 + rng() % ((u64{1} << w) - 1);
        y.insert(x);
        ref.insert(x);
    }
    int ok = 0;
    for (int i = 0; i < 5000; ++i) {
        u64 q = rng() % (u64{1} << w);
        auto it = ref.upper_bound(q);
        auto s = y.successor(q);
        ok += (it == ref.end()) ? !s : (s && *s == *it);
    }
    std::printf("keys %zu, buckets %zu (about n / w = %zu)\n", ref.size(), y.bucket_count(), ref.size() / w);
    std::printf("x-fast prefix writes per insert: %.2f (an x-fast trie alone would need %d)\n",
                double(y.top_writes()) / ref.size(), w + 1);
    std::printf("successor queries correct: %d of 5000\n", ok);
}
keys 20000, buckets 461 (about n / w = 625)
x-fast prefix writes per insert: 0.76 (an x-fast trie alone would need 33)
successor queries correct: 5000 of 5000

There are fewer buckets than n/wn / w because a bucket that has just split holds about ww keys and keeps growing towards 2w2w before splitting again, so the average size lies between ww and 2w2w.

Indirection as a general technique

The pattern used here, "put Θ(f)\Theta(f) elements into each leaf bucket, keep only one representative per bucket in the expensive top structure", is called indirection. It turns a top structure with O(f)O(f) update cost and O(f)O(f) space per element into one with O(1)O(1) amortized top-level cost and O(1)O(1) space per element, provided the buckets can be handled in the query time. It appears again in the space reduction of vEB trees, in rank and select (blocks and superblocks) and in many dynamic structures.

Note: Hashing makes the bounds expected. For a set that does not change, static perfect hash tables make every lookup O(1)O(1) in the worst case, and queries then take O(lg⁡w)O(\lg w) worst case. For dynamic sets, the worst-case deterministic version of these bounds needs more machinery; the cell-probe results of Pătrașcu and Thorup (2006) imply that, with near-linear space, O(lg⁡w)O(\lg w) cannot be beaten by more than a constant factor in a range of parameters, for example when w=(lg⁡n)cw = (\lg n)^c for a constant c>1c > 1.

Test yourself

Why does a y-fast trie store only one representative per bucket of Θ(w)\Theta(w) keys in its x-fast trie?

  1. To make queries faster than O(lg⁡w)O(\lg w)
  2. So that the O(w)O(w) space and update cost per x-fast trie element is spread over Θ(w)\Theta(w) keys, giving O(n)O(n) space and O(1)O(1) amortized top-level work per update
  3. Because x-fast tries cannot store more keys
  4. To avoid hashing

Why is the representative of a bucket kept even when the key equal to it is deleted?

  1. It is needed for the linked list
  2. Changing it would cost O(w)O(w) in the x-fast trie on every such delete, which an adversary could trigger repeatedly; as a separator it stays valid
  3. It cannot be deleted from a hash table
  4. It is the bucket's minimum by definition

What is the update bound of a y-fast trie?

  1. O(1)O(1) worst case
  2. O(lg⁡w)O(\lg w) expected amortized
  3. O(w)O(w) worst case
  4. O(lg⁡n)O(\lg n) amortized