Y-Fast Tries and Indirection
The x-fast trie answers successor queries in expected time, but it stores 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 goes into the x-fast trie, and the rest wait in small balanced trees below it.
Theorem (Willard). A y-fast trie stores keys from in words. SUCCESSOR, PREDECESSOR and MEMBER take expected time; INSERT and DELETE take expected amortized time.
Since , these are the bounds of a space-reduced van Emde Boas tree, reached with a simpler structure.
The structure
- Partition the sorted keys into consecutive buckets of between and keys each (a single bucket may be smaller when ).
- Each bucket is a balanced BST (a red-black tree) of at most keys, so searching, inserting and deleting inside it cost .
- Each bucket has a representative , and the bucket holds exactly the keys in , where is the next representative. The representatives are stored in an x-fast trie. The first representative is , so every key has a bucket.
A representative is a separator, not necessarily a stored key: deleting the key equal to leaves in place. Representatives change only when buckets split or merge.
Operations
- SUCCESSOR. Find 's bucket: the largest representative , which is a predecessor query in the x-fast trie, expected. Search the bucket's BST for the smallest key above , . If there is none, the answer is the minimum of the next bucket, reached through the x-fast trie's linked list.
- INSERT. Find the bucket and insert into its BST, . If the bucket now has more than 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 .
- DELETE. Find the bucket and delete from its BST. If it drops below keys, merge it with a neighbour (removing one representative, ), and if the merged bucket has more than keys, split it again.
Why the amortized update cost is
Every bucket that a split or merge creates has a size safely between the thresholds. A split of a bucket with keys gives two buckets of about keys. A merge combines a bucket of keys with a neighbour of between and , giving between and keys; if that is more than , it is split again into two halves of at least . So every new bucket has between about and keys, at least away from both and . Before it splits or merges again, inserts or deletes must land in it. Charging the x-fast trie update to those operations gives amortized per update for the top level, on top of the BST work.
Space. The buckets hold keys in words. There are representatives, each using words in the x-fast trie, which is as well.
The program counts the entries an x-fast trie needs for random 64-bit keys, and the entries of a y-fast trie: an x-fast trie over one representative per keys, plus one entry per key in the buckets.
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 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 search, though inserting into a list shifts up to 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.
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 in every phase, and the x-fast trie, which would need 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.
#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 because a bucket that has just split holds about keys and keeps growing towards before splitting again, so the average size lies between and .
Indirection as a general technique
The pattern used here, "put 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 update cost and space per element into one with amortized top-level cost and 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 in the worst case, and queries then take 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, cannot be beaten by more than a constant factor in a range of parameters, for example when for a constant .
Test yourself
Why does a y-fast trie store only one representative per bucket of keys in its x-fast trie?
- To make queries faster than
- So that the space and update cost per x-fast trie element is spread over keys, giving space and amortized top-level work per update
- Because x-fast tries cannot store more keys
- To avoid hashing
Why is the representative of a bucket kept even when the key equal to it is deleted?
- It is needed for the linked list
- Changing it would cost in the x-fast trie on every such delete, which an adversary could trigger repeatedly; as a separator it stays valid
- It cannot be deleted from a hash table
- It is the bucket's minimum by definition
What is the update bound of a y-fast trie?
- worst case
- expected amortized
- worst case
- amortized