Skip to content
Tech Interview Prep
Technical interview guide

Tries

A tree specialized for prefix operations over strings: each edge is a character, each path from the root is a prefix.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with container comparisons cited from CPython 3.14 and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

What is a trie, how is its node structure represented in memory, and how do fixed-array versus hash-map child pointers trade off space and time?

Answer

A trie (prefix tree) is a search tree ordered by the constituent symbols of keys rather than whole-key comparisons, where each edge or child pointer corresponds to a character, and the path from the root defines a shared prefix.

Node Representation in Memory

A trie node stores two things: a terminal indicator (a boolean flag is_terminal or a payload pointer/value) and a collection of references to child nodes indexed by symbol:

Python
# Fixed alphabet representation (e.g. lowercase ASCII, alphabet size R = 26)
class FixedArrayNode:
    __slots__ = ("children", "is_terminal")
    def __init__(self):
        self.children = [None] * 26  # 26 pointer slots per node
        self.is_terminal = False

# Dynamic representation (arbitrary alphabet / sparse branching)
class HashMapNode:
    __slots__ = ("children", "is_terminal")
    def __init__(self):
        self.children = {}           # Dynamic hash table
        self.is_terminal = False

Space and Time Trade-offs

PropertyFixed Array (Node[R])Hash Map (dict / std::unordered_map)
Branch lookup time$O(1)$ worst-case direct index offset (arr[c - 'a'])$O(1)$ average, $O(b)$ worst-case probe sequence under hash collision
Memory per node (sparse)High: $R \times \text{sizeof(pointer)}$ always allocatedLow: base table overhead + only active edges
Memory per node (dense)Low overhead: contiguous array of referencesHigh overhead: hash table buckets, load factor slack (typically 25-50% empty), key/hash storage
Cache localityContiguous chunk per node; predictable indexingPointer indirection to hash table buffer + open-addressing / bucket chasing
Alphabet flexibilityRigid: bounded small alphabets (ASCII $R=26, 128, 256$)Flexible: sparse Unicode code points, arbitrary byte streams

Worked Arithmetic

Consider storing $100{,}000$ nodes on a 64-bit architecture (8-byte pointers) with standard ASCII ($R = 256$):

  • Fixed Array: $100{,}000 \times (256 \times 8\text{ bytes}) \approx 204.8\text{ MB}$ just for pointer arrays, even if each node averages only 2 active transitions (99.2% empty pointers).
  • Hash Map: An empty hash map in Python 3.14 costs 64 bytes base. For an average branching factor of 2, a compact hash table consumes $\approx 120-180$ bytes per node: $100{,}000 \times 160\text{ bytes} \approx 16\text{ MB}$.

Conversely, if $R = 26$ (lowercase letters) and nodes are dense (average branching factor $> 15$):

  • Fixed Array: $26 \times 8 = 208\text{ bytes}$ per node.
  • Hash Map: Storing 15 entries in a hash map with standard resize thresholds (powers of two capacity 32) requires tracking 32 hash buckets, keys, and values, exceeding 350-500 bytes per node due to hash table metadata and load-factor slack.

Failure Modes & Practical Decision

  1. Fixed Array with Unbounded Alphabets (OOM Trap): Allocating fixed arrays for broad alphabets like full UTF-8 or 16-bit Unicode codepoints ($R = 65{,}536$) leads to gigabytes allocated for trivial key counts. Fixed arrays belong strictly to small, fixed alphabets ($R \le 256$).
  2. Hash Table Constant Factor Latency: While hash maps are asymptotically $O(k)$ for a string of length $k$, each hop computes a character hash, traverses map buckets, and incurs CPU cache misses. Fixed arrays compile down to a single base-pointer addition and dereference (*(node->children + offset)), often running $3\times-5\times$ faster in hot lookup paths when memory limits are not breached.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain the binary trie for integers without using the usual slogan?

Answer

A binary trie over integers is a decision tree where each level splits on one bit, most significant first. Inserting a value walks its fixed-width bit string from the top; the path from root to leaf spells the value. Two values share a node exactly as long as their high-bit prefixes agree.

That structure is what makes maximum-XOR queries greedy rather than heuristic. At bit b, if any value in the current subtree has the opposite bit to x, taking that branch sets bit b of the XOR to 1, and 2**b is larger than every lower bit combined. So the choice is forced.

Python
# Python 3.12
def insert(root, value, bits=32):
    node = root
    for b in range(bits - 1, -1, -1):
        node = node.setdefault((value >> b) & 1, {})

def max_xor(root, x, bits=32):
    node, best = root, 0
    for b in range(bits - 1, -1, -1):
        want = 1 - ((x >> b) & 1)
        if want in node:
            best |= 1 << b
            node = node[want]
        else:
            node = node[1 - want]
    return best

Trace it with bits=5, inserting 3 (00011), 10 (01010), 5 (00101), 25 (11001), then querying x = 5 (00101):

bitx bitwantbranch takenbest
4011 (exists)16
3011 (exists)24
2100 (exists)28
1010 (absent, fall back)28
0101 (absent, fall back)28

Result 28, which is 5 ^ 25. The walk reached 25's leaf, the value that maximises XOR against 5 in this set.

Alternatives, and what they cost.

ApproachQuery costBuild costGives max XOR?
Binary trieO(bits)O(n·bits)Yes
Hash set of prefixes, rebuilt per bitO(bits·n)noneYes
Hash mapO(1) exactO(n)No: no prefix structure
Sorted arrayO(log n) exactO(n log n)No: max XOR is not a range query

The prefix-set method is the real competitor: for each bit from high to low, build {v >> b} and test whether some pair of prefixes XORs to the candidate. It needs no trie and no build phase, which wins for a single query. For many queries against a fixed set, the trie's O(bits) per query beats rebuilding sets every time. Sorting is a trap worth naming: minimum XOR of a pair is achieved by adjacent elements in sorted order, but maximum XOR is not, so the sorted order that helps one query does nothing for the other.

When the trie is the wrong choice. Exact-match lookups only: a hash map is simpler and faster. Small n, where a linear scan of n·bits is fine. Large 64-bit keys: worst case is n·bits nodes, and a Python dict per node runs roughly 200 bytes, so 10^6 64-bit values can reach tens of GB. Pack the trie into two int32 children per node in a flat array, or use the prefix-set method, before you reach that scale.

Failure modes.

  • Width mismatch. Inserting 5 as 101 instead of 000...101 shifts every comparison by the missing leading zeros. Assert value < 2**bits at insert.
  • Negative values. In Python, (value >> b) & 1 on -1 yields 1 for every b, so -1 and 2**bits - 1 collide in the trie. Mask with value & ((1 << bits) - 1) before inserting.
  • Empty trie. max_xor raises KeyError on the first absent branch. Guard on a size check.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through marking the end of a key, including where engineers most often get it wrong.

Answer

Every trie node needs a marker meaning "a key ends here", stored separately from "this node has children". Those are independent facts, and the question is really about not collapsing them.

Insert walks the key from the root, creating child nodes as needed, and sets the marker on the node reached after the last character. Search walks the same path and returns true only if that final node's marker is set. starts_with walks the path and returns true if the path exists: it never reads the marker. That is the whole mechanism; everything below is what goes wrong when the marker is missing or inferred.

Python
class Node:
    __slots__ = ("children", "count")
    def __init__(self):
        self.children = {}
        self.count = 0          # 0 means no key ends here

class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, key):
        node = self.root
        for ch in key:
            node = node.children.setdefault(ch, Node())
        node.count += 1

    def search(self, key):
        node = self._walk(key)
        return node is not None and node.count > 0

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

    def _walk(self, s):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

Trace it. Insert "app", then "application", then "app" again:

callwalk ends atcount thereresult
search("app")node after a,p,p2True
search("ap")node after a,p0False
search("appl")node after a,p,p,l0False
starts_with("app")node after a,p,p—True

The "app" node has a child (l) and is still a key. The "ap" node also has a child and is not a key. Structure alone cannot tell you which.

Where engineers get it wrong. Two variants, both from the same trie above.

Path-exists as membership. If search is written as "did the walk complete", search("ap") returns True because the path exists. Every prefix of a stored key becomes a false member. This is the bug that ships, because it passes any test where no stored key is a prefix of another.

Leaf as the marker. If you infer the marker from "node has no children", search("app") returns False: the "app" node has child l. You get false negatives for exactly the keys that are prefixes of longer keys. Note the asymmetry: with inserts only, a leaf node always is a key end, so this test never produces a false positive, which is why it survives review.

Deletion is the second place it breaks. Clearing the marker is not enough; you have to decide whether to prune. Walk back up from the deleted key's node and remove nodes only while they have no children and count is 0. In the trie above, deleting "app" sets its count to 0 and stops immediately, because the node still has child l for "application". Pruning unconditionally deletes the shared prefix and corrupts "application".

Choosing the representation. The marker's type is a design decision, not a detail:

MarkerSupportsCostBreaks when
boolmembershipone field per nodeduplicate inserts, refcounted delete
int countduplicates, safe deleteone int field per node—
value slotkey→payload (weights, next-hop)pointer per keyvalue stored in children instead of its own field
sentinel childuniform "end is an edge"one extra node per keykeys are arbitrary bytes with no reserved symbol

Decide from the query, not the data: membership only → bool. Repeated inserts or delete-by-decrement → int. The trie is a map (autocomplete weights, longest-prefix routing) → store the value in its own field and treat "value present" as the marker, so a node can be both a key and a prefix. The sentinel approach is the one to avoid unless the alphabet is fixed and small, because it needs a symbol the key set can never contain.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of deletion from a trie?

Answer

The injection: delete a key that is a prefix of another key, and delete a key that was never inserted.

Those two cases are where a team's model of trie deletion breaks. Both are cheap to run and both fail loudly if the implementation prunes unconditionally.

Assume: keys are strings, each node carries an is_word flag and a children map, no duplicate keys, single-threaded.

The correct rule: clear is_word at the terminal node, then on the way back up unlink a child only if the recursive call reports that the child is now childless and not a word.

Python
def delete(node, word, i=0):
    if i == len(word):
        node.is_word = False
    else:
        child = node.children.get(word[i])
        if child and delete(child, word, i + 1):
            del node.children[word[i]]
    return not node.children and not node.is_word   # "safe to unlink me"

The bug you are hunting for returns True unconditionally, or prunes without checking is_word:

Python
def delete_buggy(node, word, i=0):
    if i == len(word):
        node.is_word = False
        return True          # always claims "unlink me"
    child = node.children.get(word[i])
    if child and delete_buggy(child, word, i + 1):
        del node.children[word[i]]
    return True

Trace both on {"app", "apple"}: 6 nodes: root, a, p, p, l, e.

callcorrect returnsbuggy returnscorrect effectbuggy effect
delete(p2, "app", 3)False (has child l)Trueclears is_word on p2clears is_word, claims unlink
delete(p1, "app", 2)FalseTruekeeps p1deletes p2
delete(a, "app", 1)FalseTruekeeps adeletes p1
delete(root, "app", 0)FalseTruekeeps adeletes a

Correct: 6 nodes, "apple" still reachable, "app" gone. Buggy: 1 node, both keys gone.

The second injection is nastier because it needs no shared prefix to be obvious: call delete(root, "apx") on the buggy version. At i=2 the lookup for 'x' returns None, the branch is skipped, and the function still returns True, so p1 unlinks p2, then a unlinks p1, then root unlinks a. The trie loses "app" and "apple" while deleting a key that was never inserted. A missing-key delete must be a no-op.

Detection: enumerate the trie after each delete and compare the key set against a Python set oracle. Run random insert/delete sequences, including deletes of absent keys, and assert equality. Also assert node count: after deleting every key, the trie should be back to 1 node (root only). That catches the opposite bug, never pruning, which leaks memory.

Alternatives and when they win:

  • Refcounted nodes: store a child count per node, unlink when it hits 0 and is_word is false. Same O(len(key)) cost, no recursion return plumbing, and it works for iterative deletion, but insert must maintain the counts, so you trade delete simplicity for insert bookkeeping.
  • Lazy deletion: clear is_word and never free nodes. Delete is O(len(key)) and trivially correct, but memory grows with every distinct key ever inserted; it wins when deletes are rare, reads dominate, or the trie is rebuilt periodically anyway.
  • Subtree rebuild: when a subtree empties, rebuild it from the surviving keys. Only worth it for batch deletes, since it costs O(subtree size) per operation.

Cost is O(len(key)) for the conditional prune, same as insert and lookup. The decision that changes with scale is lazy vs. eager: if deletes are under roughly 1% of operations, tombstones plus a periodic rebuild usually beat the bookkeeping.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

What does prefix search versus exact search guarantee, and what does it deliberately leave open?

Answer

Assume a byte-comparable key space indexed by a trie or a sorted structure. Exact search guarantees membership: the key is in the set. Prefix search guarantees only that the result set is non-empty: at least one stored key starts with the prefix. Everything else is left open: whether the prefix is itself a key, how many keys match, their order, and what it costs to enumerate them.

Both are the same descent. In a trie you walk one node per character; exact search adds a terminal check, prefix search stops at the node.

Python
class Trie:
    END = "\0"                      # sentinel: this node terminates a stored key

    def __init__(self):
        self.root = {}

    def insert(self, w):
        node = self.root
        for ch in w:
            node = node.setdefault(ch, {})
        node[self.END] = True

    def _descend(self, s):
        node = self.root
        for ch in s:
            node = node.get(ch)
            if node is None:
                return None
        return node

    def exact(self, w):
        n = self._descend(w)
        return n is not None and self.END in n

    def prefix(self, p):
        return self._descend(p) is not None

Trace with insert("car"), insert("cart"), insert("cat"):

  • exact("car") → descend c→a→r, node has END → True
  • exact("ca") → node exists, no END → False
  • prefix("ca") → node exists → True
  • prefix("cab") → descend c→a→b, b missing → False

So "ca" is a prefix of a stored key but is not itself a key. That gap is the whole distinction.

Descent is O(m) in the prefix length for both operations, with O(σ) branching per node. The difference is only the assertion at the terminal node.

What prefix search leaves open, and where it bites:

exactprefix
guaranteeskey present≥1 key with prefix
leaves open—count, order, whether prefix is a key, enumeration cost

Alternatives and their open edges:

  • Radix / Patricia tree: compresses single-child chains, so descent is still O(m) but node count drops from O(total bytes) to O(n) keys. Path compression means a node can span several characters: you must compare the remaining edge label, not just follow pointers.
  • Redis: KEYS pattern is O(N) and blocks the single-threaded server. SCAN is cursor-based and guarantees a key present for the whole iteration is returned at least once, but leaves open duplicates, ordering, and how many keys come back per call.
  • LSM (RocksDB, SSTable): prefix search is a seek to the prefix then a forward scan until the key diverges. Keys with the prefix are contiguous within each sorted run, but the cost is left open: tombstones, level count and compaction state decide it.

Failure modes: implementing prefix search as exact search that ignores the terminal check conflates "prefix exists" with "prefix is a key". It returns False for "ca" when "car" is stored. A test that inserts a key and queries a strict prefix of it catches this immediately. Assuming prefix results are sorted holds for an in-order trie traversal but not for SCAN. Assuming prefix search is cheap holds for the descent (O(m)) but not for returning matches (O(k), or O(N) for KEYS).

If the decision turns on count or ordering, prefix search alone doesn't give it: you need a bounded range scan (seek to the prefix, stop at the prefix successor) over a sorted structure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you implement autocomplete to find all words sharing a prefix, and how do you limit or rank the returned results efficiently?

Answer

Prefix autocomplete is a two-phase operation: locate the prefix node by traversing the trie, then collect completions from the rooted subtree.

1. Basic Subtree Enumeration (Exhaustive DFS)

To find all keys with prefix $P$:

  1. Descend along characters of $P$ from the root. If any edge is missing, return empty in $O(|P|)$ time.
  2. From the target node $N_P$, run depth-first search (DFS) over its descendants, accumulating paths where is_word is true.
Python
class TrieNode:
    __slots__ = ("children", "weight", "is_word")
    def __init__(self):
        self.children = {}
        self.weight = 0
        self.is_word = False

def autocomplete_dfs(root: TrieNode, prefix: str) -> list[str]:
    curr = root
    for ch in prefix:
        if ch not in curr.children:
            return []
        curr = curr.children[ch]

    results = []
    def dfs(node: TrieNode, path: list[str]):
        if node.is_word:
            results.append("".join(path))
        for ch, child in node.children.items():
            path.append(ch)
            dfs(child, path)
            path.pop()

    dfs(curr, list(prefix))
    return results

If the subtree contains $M$ total nodes, DFS visits all $M$ nodes, yielding time complexity $O(|P| + M)$ and space $O(H)$ where $H$ is the maximum key depth. On high-fanout prefixes (e.g., single characters like "a"), $M$ can span millions of keys, making unconstrained enumeration a severe latency and memory hazard for online query paths.

2. Limiting and Ranking Top-K Results

Returning all completions is rarely desirable; client interfaces typically need only top-$k$ matches (e.g., $k=10$) ranked by score or frequency.

Strategy A: Online Traversal with Min-Heap ($O(|P| + M \log k)$)

Traverse the entire subtree with DFS or BFS. Maintain a min-heap of size $k$ ordered by score. Push completions into the heap, evicting the root when size exceeds $k$. While space is bounded to $O(k + H)$, it still incurs $O(M)$ node visits.

Strategy B: Best-First Search with Max-Heap (Pruning)

Store max_subtree_weight at every node (the maximum score among all descendants). At query time, use a priority queue of trie nodes prioritized by max_subtree_weight. If the node at the top of the queue has a max_subtree_weight smaller than the $k$-th best result already found, search terminates early without exploring the rest of the subtree.

Strategy C: Precomputed Top-$k$ per Node (Zero-Traversal $O(|P|)$)

Store a precomputed list of the top-$k$ completions directly on each TrieNode during ingestion.

StrategyQuery LatencyIngestion / Update CostNode Memory Overhead
Exhaustive DFS + Heap$O(P+ M \log k)$
Pruned Best-First$O(P+ m \log m)$ ($m \ll M$)
Precomputed Top-k$O(P)$

Production Failure Modes

  1. Memory Explosion on Dense Precomputation: If a trie has $10^7$ nodes and each caches $k=10$ string references or IDs, heap memory swells by tens of gigabytes. For dynamic or large corpora, prefer Strategy B (single scalar max_subtree_weight) or limit precomputed top-$k$ strictly to nodes within depth $\le 3$, delegating deeper, smaller subtrees to online DFS.
  2. Stale Top-K Invalidation: In precomputed designs, deleting or re-weighting a high-frequency key requires an upward walk to the root, invalidating and re-evaluating top-$k$ at every ancestor. When updates are frequent, decoupled async index rebuilds or pruned best-first search are required to prevent lock contention.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on ranked autocomplete. How do you evaluate it?

Answer

Three questions decide whether the design is sound, and I'd ask them before reading any code.

1. What is the ranking signal, and is it per-user? If it's global popularity from query logs, you can precompute. If it's personalized (this user's history, their org's documents) you cannot precompute a top-k per prefix node, because the answer differs per user. That one question kills or saves most proposals.

2. How often do scores change, and do they fall? Query-log popularity shifts hourly, and a term's score decays as well as rises. A design that maintains a subtree maximum only on insertion is correct for increases and silently wrong for decreases.

3. What's the latency budget and the prefix distribution? Autocomplete is keystroke-level: p99 under ~50 ms end-to-end is a common target, and the first two characters carry most of the traffic. A design that's fine for "zebra" can fall over on "a".

The mechanism, and where it bounds work. A plain trie gives prefix matching, not ranking. Store at each node the maximum score in its subtree, then walk best-first with a priority queue: pop the highest-scoring node, emit it if it's a terminal, otherwise push its children. You stop after k emissions without touching the rest of the subtree.

Trace, k=2, prefix "c":

cat 90, car 40, cow 70, dog 55
pop c(90)  -> push ca(90), co(70)
pop ca(90) -> push cat(90), car(40)
pop cat(90) -> emit #1 "cat"
pop co(70) -> push cow(70)
pop cow(70) -> emit #2 "cow"

Five nodes visited, two emitted; "car" and the whole "d" branch are never touched. That bound is on typical work, not worst case: if the top-k all sit under one deep branch, you walk that branch. And the max must be exact: a stale max makes the result approximate, which is acceptable only if the design says so.

Alternatives, and when each wins.

DesignQuery costUpdate costWins when
Precomputed top-k per nodeO(1) per keystrokeO(prefix length × k) per score change; every ancestor rewrittenScores are global and change slowly
Subtree max + best-firstO(k log k) typical, unbounded worst caseO(prefix length) on increase; subtree recompute on decreaseLarge corpus, memory matters, global ranking
Weighted FST (Lucene-style)Fast, compactFull rebuild; immutableStatic ranking, offline rebuild is fine
External ranking serviceNetwork hop plus service latencyWhatever the service doesPersonalization or signals you can't precompute

Failure modes I'd probe. Hot prefix: one prefix ("a", "s") taking a large share of traffic concentrates load on one subtree or one shard. Detect with per-prefix latency histograms, not a global p99. Score decay: a term popular last month keeps its subtree max forever unless recomputed. Detect by diffing served top-k against a batch recompute. Memory: precomputed top-k at k=10 over a 10M-term corpus is roughly 30M trie nodes, 10 entries × 8 bytes ≈ 2.4 GB of payload before per-node overhead, which typically doubles it (worked estimate, not a measurement).

Verdict. I'd accept it if the signal is global, scores mostly rise, and the latency budget tolerates a rebuild window. I'd push back if it's personalized, if scores decay, or if top-k is precomputed against a churning corpus: those are the cases where the design is right in a demo and wrong in production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How do Trie operations compare to Hash Table operations across worst-case time complexity, cache locality, and memory overhead?

Answer

For a key of length $k$ over an alphabet $\Sigma$ with $N$ keys stored:

1. Worst-Case Time Complexity

  • Hash Table: Average-case search is $O(k)$ because hashing an arbitrary string requires examining all $k$ bytes. However, worst-case search degradations reach $O(N \cdot k)$ under hash collisions (or $O(k \log N)$ if buckets degrade to balanced trees as in Java 8+ HashMap). Resize operations also introduce an occasional $O(N \cdot k)$ amortised latency spike.
  • Trie: Search, insert, and delete are strictly $O(k)$ in the worst case (or $O(k \log |\Sigma|)$ if child nodes are stored in balanced search trees). The trie guarantees bound completion without collision degradation or table resizing.

2. Cache Locality and Memory Access Patterns

  • Hash Table: Access executes in two discrete steps: computing the hash on contiguous bytes of the query string, followed by a direct array index calculation hash % capacity. Open-addressing tables (e.g., Python's dict) yield high spatial locality when probing contiguous slots. Even closed-addressing tables typically encounter only 1–2 pointer dereferences once the bucket index is resolved.
  • Trie: Traversal requires following $k$ sequential pointers across the heap, one per character. Because tree nodes are allocated individually, these nodes rarely sit in contiguous memory. This produces up to $k$ independent L1/L2/L3 cache misses. For string lookups where $k = 32$, a trie may incur up to 32 cache misses, while a hash table typically incurs 1 cache miss to touch the bucket.

3. Memory Overhead

Data StructurePer-Key / Per-Node OverheadMemory for 1,000,000 8-char keys (ASCII)
Hash Table (e.g., open addressing)Table array entries (8–16 bytes/slot) + raw contiguous string payload~24–40 MB total
Standard Trie (Array per node: $\Sigma = 26$)Node = 26 pointers (208 bytes) + bool/flags (8 bytes) = ~216 bytes/node~300–800 MB (depends on prefix overlap)
Trie with Map/List NodesNode object header (16B) + inner Map overhead + pointers per child~100–300 MB
Python
# Concrete memory penalty illustrated in Python:
class TrieNode:
    __slots__ = ("children", "is_terminal")
    def __init__(self):
        self.children = {}  # Dict overhead per active prefix node: min 64 bytes
        self.is_terminal = False

Failure Modes & Production Guidance

  • Memory Exhaustion via Distinct Prefixes: Tries degrade severely in memory when keys share minimal prefixes (e.g., random UUIDs or cryptographic hashes). With zero shared prefixes, an 8-character string generates 8 distinct node allocations.
  • Latency Degradation via Pointer Chasing: On modern CPUs, an L3 cache miss takes ~50–100 ns. Traversing a trie of length $k=20$ with non-cached nodes costs $\sim 1\text{--}2,\mu\text{s}$, whereas computing a hash in CPU registers and reading a single slot costs $<100,\text{ns}$.

Use a hash table when exact key lookup is the only access pattern. Reach for a trie when query semantics strictly require prefix matching, longest prefix matching (e.g., IP routing), or lexicographical key enumeration.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

When should you choose a trie over a hash map for ordered traversal, range queries, and longest-prefix matching, and when does the hash map win outright?

Answer

Choose a trie when the workload needs ordered traversal, range queries, or longest-prefix matching. A hash map gives O(1) average exact lookup but has no order, so any ordered operation forces a full scan or a sort. A trie stores keys by character, so an in-order traversal yields lexicographic order in O(n). For a range query [a, b], you walk to the node for a, then iterate in-order until you pass b: O(L + k) where L is the length of a and k is the number of keys returned. Longest-prefix matching is O(L): walk down the query string, remembering the last terminal node. A hash map cannot do that without checking every prefix, which is O(L^2) if you hash each prefix.

Here is the longest-prefix match in a trie:

python class TrieNode: slots = ('children', 'is_end') def init(self): self.children = {} self.is_end = False

def longest_prefix(root, s): node = root best = -1 for i, ch in enumerate(s): if ch not in node.children: break node = node.children[ch] if node.is_end: best = i return s[:best+1] if best >= 0 else None

For range queries, suppose keys are apple, app, apricot, banana. Range [app, apricot]: traverse to app, then in-order gives app, apple, apricot. That is three keys, no sorting.

OperationHash mapTrie
Exact lookupO(1) avgO(L)
Ordered iterationO(n log n) (sort keys)O(n) in-order
Range query [a,b]O(n) scan or O(n log n) sortO(L + k)
Longest-prefix matchO(L^2) naiveO(L)

Hash map wins outright when you only need exact key lookup and no ordering or prefix operations. It also wins when memory is tight: a trie's node overhead can be 10-50x the raw key bytes, especially with hash-map children. And when keys are not strings or share no prefixes, the trie's advantage disappears. Hash maps also have better cache locality for random lookups because they touch one bucket, while a trie chases pointers down the key length.

The failure mode for a trie is memory blowup and poor cache behavior. For a hash map, it is that you will end up sorting keys on every range query, which turns an O(1) structure into an O(n log n) one. Python's dict preserves insertion order but not sorted order, so it does not help for range queries. Java's HashMap does not guarantee order at all. If you need ordered operations but not prefix sharing, a balanced BST like Java's TreeMap is another option, but it is not a hash map. So the decision is: if ordered traversal, range queries, or longest-prefix matching are in the requirements, use a trie (or a balanced BST if you do not need prefix sharing). If they are not, use a hash map.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does children as arrays versus maps matter, and where is it irrelevant?

Answer

Short answer: it matters when the alphabet is large or sparse and the trie is memory- or latency-bound. It is irrelevant when the alphabet is small and dense, when the whole structure fits in cache, and for any asymptotic complexity claim: both give O(1) per hop in the RAM model.

Mechanism. An array node is one contiguous allocation. In CPython 3.12 on 64-bit, [None] * 26 is a 56-byte list header plus 26 pointers = 264 bytes, whether the node has 1 child or 26. A dict node is a compact hash table: sys.getsizeof({}) is 64 bytes and a one-entry dict is ≈184 bytes, growing in steps as it resizes. So a one-child node is smaller as a dict (184 vs 264) and a 26-child node is smaller as an array (264 vs several hundred bytes). The crossover sits somewhere around 6–10 children.

The latency side is cache lines, not bytes. The array's 26 child pointers live in the same ~4 cache lines as the node header, so once you have loaded the node you usually have the child pointer too: one dependent load per hop. A dict lookup hashes the symbol, indexes the indices table, then follows into the entries table, which is a separate allocation: two or three dependent loads, each a potential miss. A DRAM miss is ~80–100 ns; an L1 hit is ~1 ns. On a trie with a hot working set the array wins by tens of ns per hop; on a cold, memory-bound trie the dict's smaller footprint wins by fitting more nodes in cache.

RepresentationBytes per node (CPython 3.12, 64-bit)Per-hop costBest when
[None] * 26264 B, fixed1 dependent load; child pointer shares cache lines with the headerdense alphabet, high branching, latency-bound
{}≈184 B at 1 entry, grows with entrieshash + 2–3 dependent loadssparse alphabet, low branching, memory-bound
[None] * 0x1100008.9 MB per node—never

Where it is irrelevant.

  • Small dense alphabets. Digits (10) or DNA (4). A 4-slot array is 88 bytes; a dict is 184. The array wins on both axes, so there is no trade-off to reason about.
  • Cache-resident tries. If the whole structure is under ~32 KB (L1 is typically 32–48 KB), both fit and the per-hop difference is a few ns: below the noise of your own benchmark.
  • Asymptotic analysis. Insert, lookup and delete are O(key length) either way. If the interview question is about complexity, the representation is a constant factor, and saying so is the correct answer.
  • Compressed tries. A radix/Patricia trie removes the low-branching nodes entirely, so the per-node representation stops mattering.

Failure mode. Choosing the 26-slot array and then needing arbitrary Unicode keys. Every node operation changes, and it survives casual testing because ASCII test data never exercises the missing slots. Detect it by asserting the key domain at construction and by running tracemalloc over a realistic key set.

Real systems do not pick one. The Adaptive Radix Tree (Leis et al., 2013) uses Node4/Node16/Node48/Node256 and promotes a node as it fills: the same crossover, implemented adaptively. That is the senior answer: fix the alphabet from the key domain, then let the node type follow the branching factor.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

A standard trie over lowercase ASCII with 1M keys is blowing the memory budget. Quantify what it actually costs, then tell me how you'd bring it down and when the overhead is worth paying at all?

Answer

The arithmetic first. A standard trie node over a 26-letter alphabet is a 26-slot child array plus a terminal flag. On 64-bit, that's 26 × 8 = 208 bytes of pointers, plus 1 byte for the flag padded to 8, so 216 bytes per node in C. In Java, add a 12–16 byte object header, so ~224–232 bytes. The node count is the number of distinct prefixes in the key set. Worst case: no shared prefixes, e.g. random UUIDs or hashes: that's N × L nodes for N keys of average length L. With 1M keys of length 10, that's 10M nodes × 216 bytes ≈ 2.16 GB. Shared prefixes help: 1M English words of average length 10 have roughly 2–3M distinct prefixes, so ~500 MB. Still 10–20× the raw string bytes.

Comparison table.

StructureBytes per nodeNodes for 1M keys, L=10TotalPrefix ops?
Array trie (σ=26)21610M worst, ~2.5M shared2.16 GB / 540 MByes
Hash map~48 per entry + string1M entries~80 MBno
Sorted array~26 per key + string1M~30 MBbinary search only
Radix trie~60~2M (branch + leaf)~120 MByes
TST~3210M worst, ~2.5M shared320 MB / 80 MByes

How to bring it down. Three levers, in order of impact.

  1. Compress chains. A radix trie (Patricia trie) collapses every chain of single-child nodes into one edge labeled with a substring. Node count drops from O(N×L) to O(N): one leaf per key plus branching nodes. For 1M keys that's ~2M nodes regardless of key length. Each node stores a (pointer, length) slice plus a small child map, ~60 bytes. Total ~120 MB. Cost: insertion and deletion must split and merge edges, and the code is materially harder to get right.

  2. Drop the alphabet-sized array. A ternary search tree stores one character per node with three pointers (left, equal, right) and a terminal flag: ~32 bytes. No 26-slot array, so it handles large or sparse alphabets without waste. Node count is the same as a standard trie (one node per character, shared prefixes share the equal-child chain), so 10M nodes worst case = 320 MB. Lookup is O(L + log σ) expected, not O(L).

  3. Shrink the node. If the alphabet is small and dense (DNA, 4 symbols) an array trie is already compact: 4 × 8 = 32 bytes + flag = 40 bytes per node. For sparse alphabets, a hash map per node costs ~184 bytes for a one-child node in CPython 3.12, which is worse than the array until ~6–10 children.

When the overhead is worth paying. Pay it when you need operations a hash map cannot give you: ordered traversal, range queries, longest-prefix matching, autocomplete. A hash map answers exact lookup in O(1) and uses ~80 MB for the same 1M keys; a sorted array uses ~30 MB and supports binary search. If your workload is exact lookup only, the trie is strictly worse on memory and usually on speed. If you need prefix search and memory is tight, radix trie or TST. If the alphabet is tiny and dense, the plain array trie is fine.

Failure modes. The one that bites is assuming shared prefixes save you. For random keys (UUIDs, hashes, session tokens) sharing is near zero, so node count is N×L and the 2.16 GB estimate is the real one. Detect it before building: compute the distinct-prefix count on a sample. Second: storing a value pointer at every node adds 8 bytes × node count; if values only live at terminals, say so. Third: Unicode. σ=1,114,112 code points makes an array node impossible; you must use maps or a TST, and normalisation (NFC vs NFD) changes the prefix structure. Fourth: a 2 GB trie doesn't fit in cache, so every hop is a DRAM miss (~80–100 ns) and traversal becomes latency-bound, not compute-bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How does a compressed trie optimize space over a standard prefix tree, and what trade-offs does it introduce during insertion and deletion?

Answer

Core answer (first 90 seconds). A compressed trie (radix tree, Patricia trie) deletes every node that has exactly one child and does not terminate a key, folding the characters along that chain into a single edge label. For N keys the node count drops from O(N·L) to at most 2N−1, independent of key length L. What you pay for it is mutation: insertion becomes an edge split, deletion becomes a node merge, and both mutate nodes that already exist instead of appending fresh ones. Edge labels are normally stored as (offset, length) slices into the key buffer, so the space win is real only if that buffer is stable and the child representation is compact.

Mechanism

In a standard trie every character gets a node. A compressed trie keeps only branching nodes (out-degree ≥ 2) and terminal nodes, so every internal node has at least two children: the root included, except when N = 1. N leaves plus at most N−1 internal nodes gives the 2N−1 bound.

Standard trie (keys: car, cat, dog)      Compressed trie
root                                     root
 ├─ c                                     ├─ "ca" ─┬─ "r" → car
 │   └─ a                                 │        └─ "t" → cat
 │       ├─ r → car                       └─ "dog" → dog
 │       └─ t → cat
 └─ d
     └─ o
         └─ g → dog
8 nodes                                  5 nodes

What the node count actually buys

Example, labelled as such: 1M lowercase keys, average length 10.

LayoutNodesBytes/nodeTotal
Standard trie, 26-way pointer array~10M26×8 + ~16 header ≈ 224~2.2 GB
Compressed, same node layout≤ 2N−1 ≈ 2M224~450 MB
Compressed, slice edges + sorted child array (radix trees average 2–3 children)~2M~48~100 MB

The node-count win alone is a factor of ~L/2. The rest comes from shrinking per-node overhead, which is a separate decision.

Insertion and deletion

insert(key):
  node = root; i = 0
  while i < len(key):
    child = find_child(node, key[i])
    if child is None:
      node.add_edge(key[i:], leaf(key)); return
    label = child.label
    j = lcp(key[i:], label)          # 1 <= j <= len(label)
    if j == len(label):
      node = child; i += j; continue # whole label matched, descend
    child.label = label[j:]          # old child keeps the tail
    mid = new_node()
    mid.add_edge(label[j:], child)
    mid.add_edge(key[i+j:], leaf(key))
    node.replace_edge(label[:j], mid)
    return

Trace, inserting car, cat, dog in that order:

  1. car: empty tree, root gets one edge "car" → leaf.
  2. cat: LCP with "car" is "ca" (j = 2). Split: root → "ca" → {"r" → car, "t" → cat}. 4 nodes.
  3. dog: LCP with "ca" is empty, so no split; add edge "dog" → leaf. 5 nodes = 2N−1.

Deleting cat: the "ca" node drops to one child ("r" → car) and is not terminal, so it must coalesce. Concatenate "ca" + "r" into "car" and point the root straight at the car leaf. 5 nodes → 3. Skip that step and the unary chain survives.

OperationStandard trieCompressed trie
Max nodes (N keys)O(N·L)≤ 2N−1
Internal out-degree1 to R≥ 2 (or terminal)
Insertallocate missing character nodesLCP match + conditional edge split
Deleteclear terminal flag, prune dead pathclear flag + merge single child into parent
Edge labelimplicit, one symbol per hopslice (offset, len) or string pointer

Lookup stays O(L): label comparisons along a path consume at most L characters total, plus the per-node child lookup (O(log R) sorted, O(1) for a 256-way array).

Failure modes

  • Heap-allocated edge strings. If each split allocates a fresh string instead of slicing a stable buffer, ~1M splits means ~1M small allocations; allocator headers and fragmentation can erase the node-count win entirely.
  • Slices into a reallocating buffer. If keys live in a std::string or vector that grows, stored offsets dangle. Use an arena or store indices.
  • Deletion without coalescing. Unary chains reappear; after deleting half the keys the tree drifts back toward O(N·L) nodes and lookup does more pointer hops per character.
  • Concurrent split. A reader traversing an edge while a writer splits it can see a torn label. Linux's radix tree uses RCU; ART uses optimistic lock coupling with version counters. Without one of those you need a global lock and lose read scalability.

When not to use it: fixed-length short keys (8-byte hashes, integer IDs). A hash table or a plain array beats it. Static key sets are usually better served by a sorted array plus binary search or a suffix array, which avoid the mutation machinery altogether.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does the double-array and succinct forms interact with rollback, and where do people ignore that?

Answer

Rollback here means undoing a batch of updates to restore a prior state: a transaction abort, a failed bulk load, a versioned index that must still serve an older snapshot. The thing to get right is that both double-array and succinct tries are flat arrays, so rollback is a question about array state, not about walking a pointer graph. The trap is that a single double-array insertion can rewrite slots nowhere near the key you inserted.

Double-array invariant: two int32 arrays, base[] and check[]. A transition from node s on character c lands at slot t = base[s] + c, and check[t] == s confirms it. Inserting a child of s needs a base[s] where every required slot is free (check == 0). If none exists, you relocate s: pick a new base, move s's own slot, and rewrite check[] for every child of s to point at the new index. One insertion can therefore touch many slots.

Worked trace (1-indexed, index 0 unused, alphabet a=1, b=2):

  • base[1]=1, check[1]=0. Insert "a": slot 1+1=2 free → check[2]=1, base[2]=2.
  • Insert "aa": from node 2, slot 2+1=3 free → check[3]=2, base[3]=4.
  • Insert "b": from root, slot 1+2=3, but check[3]=2 → conflict. Relocate root: base[1]=4 gives slots 5 and 6 free. Move node 2 from slot 2 to slot 5 (check[5]=1, base[5]=2; clear check[2], base[2]). Node 2's child sits at base[5]+1=3, so check[3] must become 5. Then insert "b" at slot 4+2=6: check[6]=1, base[6]=7.

That one insert wrote eight slots: base[1], check[5], base[5], check[2], base[2], check[3], check[6], base[6]. An undo log that records only "insert b at slot 6" restores two of them and leaves the array inconsistent.

Succinct (LOUDS) stores topology as a bitvector in level order, 2 bits per node, plus a label array. Insertion shifts the bits after the insertion point, O(n) worst case, or O(log n) with a wavelet-tree/B-tree of bitvectors. Rollback has the same shape: snapshot the bitvector, or undo the shift.

Rollback strategyDouble-arraySuccinct
Physical write logevery slot written, incl. relocationsbitvector edits
Snapshotcopy base[]+check[] (8 B/slot)copy bitvector (2 bits/node)
Copy-on-write pagesversion touched pagesversion touched blocks

Worked sizes, assuming int32 arrays and 1M nodes: double-array snapshot ≈ 8 MB; LOUDS topology ≈ 250 KB; a node-object trie with per-node child maps ≈ 100 MB. Snapshotting a succinct index per transaction is cheap; snapshotting a double-array per transaction is not.

Where people ignore it:

  • Logging logical ops ("insert W") and undoing with "delete W". Delete clears check but does not move the relocated node back, so the array is logically equivalent but not byte-identical. That breaks checksum-based replication, snapshot diffing, and deterministic replay across replicas.
  • Forgetting free-slot state. After rollback the free set differs, so the next insert picks different base values and layouts diverge between replicas.
  • Treating succinct as immutable and bolting on a mutable overlay without a rollback path for the overlay; merging the overlay into the base is not reversible.

Detection: hash base[] and check[] (or the bitvector) before and after a rollback and assert equality; replay the same insert sequence twice and diff the layouts; count slot writes per logical operation. A number far larger than the key length means relocation is happening.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does persistence and rebuild force that a junior answer usually skips?

Answer

The trade-off in one line: rebuild-from-keys pays O(total key length) on every cold start and gives up warm state, but the artifact on disk is just the keys, so it survives any change to your node layout. Persisting the trie buys near-instant startup and shareable read-only state, but the file encodes your in-memory layout, so every refactor becomes a migration.

Why the trie is derivable and the pointers are not. The trie is a pure function of the key set: same keys in, same structure out (child ordering aside). Nothing about it needs storing. The pointers are addresses (they differ between runs (ASLR), between processes, and between machines) so "persist the trie" can only mean "persist a serialized encoding of the trie", which is a second data structure you now own and version.

Arithmetic (hypothetical, labelled). 100,000 English words, mean length 8.5 → 850,000 characters. Distinct prefixes run ~1.4× the character count for a word list, so ~1.2M nodes. A CPython node with __slots__ plus a child dict is ~120 bytes → ~145 MB resident, and 850k inserts at ~1.5 µs each is ~1.3 s of cold start. A flat encoding (4-byte child indices, one per edge, plus a terminal bitmap) is ~5 MB and mmaps in ~10 ms. The persisted form is ~30× smaller and ~100× faster to load, and it is a different representation from the one you query.

Rebuild from keysPersist serialized graph
Cold startO(total key length), ~1.3 s at 850k charsmmap/read, ~10 ms
Diskkeys only, ~8 MB text~5 MB flat, but a format you own
Refactor node layoutfreemigration or version bump + rebuild
Cross-process sharingnoyes, read-only mmap
LookupO(key length)O(key length)

Deciding criteria. Cold-start frequency dominates. A long-lived service that starts once a day should rebuild: 1.3 s is noise and you keep the format-free property. A per-request lambda or a CLI that starts per invocation cannot afford it; persist. Corpus size is the second axis: rebuild cost is linear, so at 10M keys the same code takes tens of seconds and the decision flips regardless of start frequency. Third: how often does the node layout actually change? If you are still iterating on the structure, persisting means a migration on every change, and you will end up rebuilding anyway, so persist only once the layout is stable.

Failure modes.

  • Format rot. You add a field to the node struct, forget to bump the version, and the loader reads garbage into a valid-looking trie. Detect with a magic number + version + checksum in the header, and fail loud rather than best-effort.
  • Dev-corpus blindness. 1,000 words rebuilds in ~2 ms; the production corpus takes seconds. The dev machine never shows it. Detect by timing cold start on a production-sized corpus in CI, not on the fixture.
  • Pointer serialization. Writing raw addresses "works" in the process that built the file and segfaults or reads nonsense in the next. Serialize indices/offsets, never addresses.

Cheapest middle ground. Persist the sorted key list and binary-search it: no format to maintain, but lookup degrades from O(key length) to O(key length × log n) string comparisons. Named alternatives that do the encoding for you: a DAWG or an FST (Lucene's term dictionary is an FST), or marisa-trie in Python.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of the suffix trie and its size?

Answer

I refuse when the text is large enough that the quadratic node count breaks the memory budget, or when the design builds a suffix trie over the full corpus rather than a bounded window. For a text of length n, a suffix trie has one node per distinct prefix of every suffix, which is O(n²). For n = 1,000,000 that is about 5×10¹¹ nodes. Even at 8 bytes per node (optimistic, since a real node carries a child map and a suffix link) that is 4 TB. At 100 bytes per node it is 50 TB. No production machine in the interview story has that, so the design is refused.

The mechanism is simple: every suffix is a path from the root, and the trie does not share the unary chains that a suffix tree compresses. A suffix tree brings the node count to O(n); a suffix array stores the starting positions of the sorted suffixes as n integers. The table shows the gap.

nsuffix trie nodes (≈ n²/2)trie memory @ 8 B/nodesuffix array @ 4 B/intsuffix array + LCP @ 4 B each
10³5×10⁵4 MB4 KB8 KB
10⁴5×10⁷400 MB40 KB80 KB
10⁵5×10⁹40 GB400 KB800 KB
10⁶5×10¹¹4 TB4 MB8 MB

The failure modes are concrete. First, OOM during build: the process dies before the first query. Detect it with memory profiling (tracemalloc, /usr/bin/time -v, a heap dump) and with a test that asserts the node count stays below a budget for a production-size corpus. Second, quadratic build time: at n = 10⁵ there are 5×10⁹ nodes; even at 100 ns per node that is 500 seconds. Detect it by timing a build on 1/10 of the corpus and checking whether 10× input costs 100× time. Third, cache and GC cost: each node is a separate object, so pointer chasing and allocation dominate. Detect it with LLC-miss counters and GC logs; the operational cost is latency spikes and memory fragmentation that a suffix array avoids by storing contiguous integers.

When not to refuse: n is small (say ≤ 10⁴, and even then only if the memory budget allows the 400 MB that 5×10⁷ nodes cost at 8 bytes each), or the trie is built over a bounded window such as the last 10⁴ characters. If the design only needs substring search, a suffix array with an LCP array gives O(m log n) query time with binary search, or O(m + log n) with an LCP-LR array, and linear memory; an FM-index gives O(m) query time with similar memory. Refuse the suffix trie and propose one of those.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What would you measure before treating wildcard matching as settled?

Answer

What I'd measure, in order: node visits per query (the branching work itself, not wall clock) then the p99/p999 of that distribution at the wildcard density real traffic shows, then a differential correctness check against a reference matcher. Latency and throughput come after, because they are downstream of the visit count and much noisier.

Assumptions to state first: a trie over a fixed dictionary, . matches exactly one character, queries are read-only. Change any of those and the measurements change.

1. Node visits per query, instrumented. Wall clock hides the mechanism; a counter does not.

Python
def count_visits(node, s, i):
    if i == len(s):
        return node.is_word, 1
    if s[i] == ".":
        total, hit = 1, False
        for c in node.children.values():
            m, v = count_visits(c, s, i + 1)
            total += v
            hit = hit or m
        return hit, total
    child = node.children.get(s[i])
    if child is None:
        return False, 1
    m, v = count_visits(child, s, i + 1)
    return m, v + 1

Trace it on a trie holding {"cat", "car", "dog"} with query "c.t": the . at index 1 has one child (a), which walks the fixed t to a word node. The call returns (True, 4): 4 visits. Move the wildcard to the front (".at") and the matcher tries all 26 root children, each walking the fixed suffix; most fail on the next character, but the count is now bounded by 26 × suffix length instead of a single path. That ratio is the thing to measure.

2. The distribution, not the mean. Report median and p99 visits bucketed by wildcard count. Illustrative figures for a 100k-word English dictionary, 9-character patterns, wildcards at random positions:

wildcards kmedian visitsp99 visits
01010
134210
21903,400
31,10041,000
46,800260,000

The mean is useless here: at k=2 the median is 190 but the p99 is 3,400, and the p99 is what a user feels. The shape: roughly multiplicative in k until the pattern is unconstrained enough to visit whole subtrees: is the finding.

3. Wildcard density in real traffic. The visit distribution only matters weighted by how often wildcards appear. Measure the fraction of queries containing at least one ., and the distribution of k. If 0.1% of queries carry a wildcard, a 12 ms p99 on those is invisible in the aggregate; if 5% do, it sets the service's p99.

4. Latency and throughput at that density. Replay a query mix with the measured wildcard density against the trie, single-threaded first, then under the target concurrency. Watch for the trie's pointer-chasing surfacing as cache misses: visits per query is the algorithmic cost, but misses per visit is the constant that decides whether 260,000 visits is 2 ms or 20 ms.

5. Correctness oracle. Before any of the above means anything, differential-test the matcher against a reference, Python's re with the literal parts escaped and . left as ., on random strings and random patterns. A fast wrong matcher measures nothing.

Failure modes. Benchmarking only wildcard-free queries and calling it settled; the happy path hides the branching. Reporting the mean visit count, which the tail dominates. Measuring on a warm cache with a dictionary that fits in L2 and generalising to one that does not.

When the numbers say stop. If p99 visits at the real wildcard density stays under a few thousand and p99 latency is inside budget, bound k (reject patterns with more than, say, 3 wildcards) and ship. If not, the fix is structural: an inverted index over character positions, or a suffix automaton. Re-run the same five measurements to confirm it moved the tail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does the Aho-Corasick automaton change if the workload grows by two orders of magnitude?

Answer

Core answer. Assume 100x means both axes grow: 5k → 500k patterns (~10M trie nodes) and 10 MB → 1 GB of text. The scan does not change: it is O(text length + matches) either way, and 10^9 steps at ~2 ns/step is a couple of seconds. What changes is the automaton's footprint and the cost of building it, and that is what you redesign.

The default dense representation is a goto table of 256 int32 per node for a byte alphabet. At 10M nodes that is 10M × 256 × 4 B = 10.2 GB, and construction writes 2.56 × 10^9 entries. At 100x you OOM during construction, not during the scan. The fix is a different transition representation, and possibly sharding the pattern set.

Mechanism, briefly. Build a trie of the patterns; a failure link points to the longest proper suffix of the current prefix that is also a prefix of some pattern; BFS assigns them; the scan follows goto edges, falls back along failure links on a miss, and emits matches at terminal nodes.

What actually changes at 100x.

RepresentationMemory @10M nodesTransitionConstruction
Dense goto (256 × int32)~10.2 GBO(1)2.56e9 writes
Double-array trie (base/check)~80 MB (8 B/node)O(1)expensive, rebuild-only
Sorted edge arrays~100 MB (~1 edge/node)O(log out-degree)sort edges once

Double-array keeps O(1) transitions at 1/128th the memory, but construction is the hard part: finding free slots for 10M nodes takes minutes and dynamic insertion is impractical, so you rebuild on pattern-set change. Sorted edge arrays are cheaper to build and cache-friendlier, at the cost of a binary search per step.

Alternatives. Wu-Manber is often better for many short patterns over large text: it hashes the last B characters and skips. A regex engine (RE2) builds a DFA with the same state-explosion risk and less control. Sharding the pattern set across N machines and scanning the text in parallel drops per-shard memory linearly; you merge match lists at the end.

Failure modes and detection.

  • Construction OOM: watch RSS and node count during build, not during scan.
  • Rebuild cost: if patterns churn, build wall time dominates. Measure it; cache the automaton when the set is stable.
  • Cache/TLB misses: every step is a dependent random load, so dense tables thrash. Detect with perf stat -e LLC-misses.
  • Failure-link chains: a single character can cost O(max pattern length). Trace: patterns {"aaab"}, text "aaac". After aaa, the c misses goto, fails to aa, misses, fails to a, misses, fails to root: 4 traversals for one character. Amortised it is O(1) per character, but adversarial long common prefixes produce latency spikes that a happy-path test never shows.

The senior move: keep the linear scan, replace the transition table, and measure construction time and RSS before trusting the design at scale.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

A vendor promises building failure links is handled for you. What do you still own?

Answer

The vendor builds the transition function. You own everything that feeds it and everything that reads its output.

Say that in the first 30 seconds, then name the five pieces:

  1. The pattern set. An automaton is exactly as good as the strings compiled into it. Adding a pattern is a release: you own the lexicon's contents, its review, and which version the vendor's build is on.
  2. Normalisation before the automaton. Case folding, Unicode form (NFC vs NFKC), URL and base64 decoding, homoglyphs. Compile Visa into the automaton and feed it raw bytes, and VISA is a silent miss.
  3. The match state across chunk boundaries. A streamed document arrives in arbitrary chunks. The automaton's current state is the whole memory of the partial match, so whoever frames the chunks has to carry it.
  4. What a match means. Overlapping hits ending at the same offset, longest-versus-all, severity, dedup across the seam. Failure links produce a match set; they say nothing about which element raises a ticket.
  5. The proof that none of it is silently wrong. A differential test against naive search.

Trace: patterns {he, she, his, hers}, one stream delivered as s then he.

  • Chunk 1: root -s-> state s. No output.
  • Chunk 2 with state carried: s -h-> sh -e-> she, emitting {she, he}. he is the suffix match reached through the fail link at the same end offset.
  • Chunk 2 with state reset per chunk: root -h-> h -e-> he, emitting {he} only.

Nothing errors. You get a 200 and a missed match. The vendor's automaton is correct in both runs; the boundary it never saw is the part you own.

You ownFailure mode if you skip itHow you detect it
Pattern set and its versionA long stream starts under lexicon v14 and finishes under v15 mid-rebuild, reporting matches no single lexicon ever producedPin one version per stream and log it on every match
Decoding to code points before the automatonA multi-byte UTF-8 character split across two chunks decodes as two invalid sequences, so any pattern containing it stops matchingReplay a multi-byte corpus with a chunk boundary at every byte offset
Automaton state across chunksThe trace aboveRun the same corpus as one buffer and as N random chunks; the two match sets must be identical
Match policy and deduphe and she end at the same offset, and a first-match-wins pipeline drops the more specific oneAssert the expected match set, not a boolean hit
Differential testDiagnosis stalls: you cannot tell a wrong automaton from a wrong callerNaive search over every pattern on random inputs; it is slow and obviously correct, which is exactly what you want from the oracle

The trade-off that decides the design: can you snapshot the automaton's state? If the vendor exposes it, carry one small struct per open stream and you stay exact. If the API is stateless (send a buffer, receive matches) you fall back to an overlap buffer holding the last (longest pattern length - 1) bytes of the previous chunk and re-scan the seam. That costs memory proportional to your longest pattern per open stream, and it makes seam matches appear twice, so dedup by (pattern, end offset) becomes mandatory rather than nice.

The deciding question is whether the vendor hands you automaton state and a versioned pattern set. If yes, buy it and spend the saved effort on the lexicon. If no, you have bought the automaton and are paying for the framing, and the overlap buffer is where the bug will be.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is case, normalisation, and Unicode?

Answer

I'd treat this as a review of a canonicalisation contract, not a style pass. The first thing I look for in the diff is whether there is exactly one function that maps a user string to a lookup key, and whether every write path and every read path calls it. If insert calls .lower() and query calls .casefold(), or one side normalises and the other doesn't, the PR is wrong regardless of how the rest of it looks.

Then four decisions, each of which I want stated in the code or the PR description.

Which normalisation form. NFC is the default for storage keys: it composes, is reversible, and doesn't change meaning. NFKC is compatibility normalisation: it folds fi (U+FB01) to fi, ① to 1, ㎏ to kg, full-width A to A. That is often what you want for a search index and almost never what you want for a key that has to round-trip, because it is lossy. If the PR uses NFKC, I want the reason written down.

Which fold. str.lower() is not case folding. "ẞ".lower() is "ß"; "ẞ".casefold() is "ss". So "STRASSE" and "straße" collide only under casefold. Use casefold() for keys, and never a locale-aware lower: Turkish dotless ı makes "I".lower() locale-dependent, a bug that only shows up in one market.

Order of operations. Fold first, then normalise, because folding can produce decomposed sequences. This is not cosmetic:

Python
import unicodedata
s = "\u0390"                      # ΐ, iota with dialytika and tonos
a = unicodedata.normalize("NFC", s).casefold()
b = unicodedata.normalize("NFC", s.casefold())
a == b            # False
len(a), len(b)    # (3, 1)

Same input, two keys. If one path folds-then-normalises and the other normalises-then-folds, lookups miss for exactly these characters and pass for everything in the test fixtures.

What's stored. Keep the original string for display and the folded key for lookup. Overwriting the user's input is unrecoverable.

Failure modes I'd name in review comments: asymmetric canonicalisation, which produces stored keys that can never be found and failures that look random; length expansion, since ß → ss and NFKC both grow the string, so a VARCHAR(255) key column can overflow after folding; and regex matching that assumes ASCII, because re.IGNORECASE doesn't do full folding and \w is Unicode-aware on str but not on bytes.

Tests I'd ask for before approving: a property test that key(x) == key(normalize(x)) over a corpus, plus explicit cases. İ (U+0130), ß, fi, a combining-mark pair like cafe\u0301, and a full-width string. And if the policy changed, a backfill: existing rows were keyed under the old rule and won't match.

The deciding criterion is whether the key must round-trip. If it must, NFC plus casefold, original preserved. If it's a search index where aggressive matching is the point, NFKC is defensible: say so, and accept the collisions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on alphabet size in the complexity, and what does not?

Answer

Core answer (first 90 seconds). A runbook section on alphabet size exists to stop two errors: quoting O(k) for operations that carry the factor, and quoting the factor for operations that don't. So it holds four concrete items and excludes three.

Include:

  1. The value of A for this system and where it comes from: 26 for lowercase ASCII keys, 256 for byte keys, 65536 for UTF-16 code units. A is the number of distinct symbols at one position, not the number of keys.
  2. Which operations carry the factor, with the child representation named: enumeration and wildcard search carry it; insert/search/delete of a single key do not.
  3. The per-node memory arithmetic for array children: A slots × 4 bytes (compressed oops, 64-bit JVM, heap under 32 GB) = 104 B at A=26, 1 KB at A=256, 256 KB at A=65536.
  4. The switch point: when the average branching factor sits well below A, array children waste memory and a hash map or sorted array wins.

Exclude:

  1. The factor from lookup/insert/delete bounds: those are O(k) whatever A is.
  2. Any bound that doesn't name the child representation: the factor is a property of the representation, not of "a trie".
  3. The wildcard exponent A^w unless A and w are both defined on the page.
ItemInclude?Why
A and its sourceyes26 vs 256 vs 65536 moves memory by four orders of magnitude
A in insert/search/deletenoone child per level, O(k)
A in enumerationyesvisits every node in the subtree
A in wildcard searchyes, with A and w definedeach wildcard fans out to ≤ A children
A in per-node memoryyesA slots allocated per node
A^w with A or w undefinednounverifiable

Mechanism. Lookup escapes the factor because it consumes exactly one child per level: with array children that is one O(1) index, so k levels cost O(k). Enumeration cannot escape it: collecting every key under a prefix walks the whole subtree, so the cost is O(total nodes visited) = O(sum of the lengths of the returned keys). The naive O(m·k) for m keys of length k overstates it whenever keys share a prefix, because the shared prefix is visited once. Wildcard search with w wildcards fans out to up to A children at each wildcard position, giving up to A^w paths of length k, so O(A^w · k) node visits worst case, bounded by the trie's node count.

ChildrenLookup stepEnumerate / iterateMemory per node
Array indexed by symbolO(1)O(A)A slots
Sorted array + binary searchO(log A)O(#children)#children slots
Hash mapO(1) expectedO(#children)#children entries + overhead
Linked listO(A)O(#children)#children slots

Failure mode. A service storing 10M byte-string keys (A=256) with array children allocates 1 KB of slots per node. If the trie holds 50M nodes, that is ~50 GB of slot arrays alone, while the average branching factor is near 1. Detection: a heap profile showing the node-array class dominating, and nodes/edges ratio close to 1. Fix: hash-map children, which allocate per child rather than per symbol.

So the runbook section states A, names the representation, gives the memory arithmetic, and lists the operations that carry the factor, and leaves out the factor everywhere it does not apply.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How should on-call treat an alert that names counting with tries as the cause?

Answer

What a strong candidate says first

An alert that names a data-structure technique as the cause is a hypothesis someone baked into a monitor, not a diagnosis. Treat it as a lead: confirm the mechanism is actually firing before you touch anything, and be ready to kill it. The first question is whether the alert's own signal is real: is the latency or memory actually off, or is the threshold wrong? Look at the dashboard the alert points at, not the alert text.

What the alert is claiming

"Counting with tries" means each node stores the number of keys in its subtree, so "how many keys start with this prefix" is one descent to the prefix node and a read of its counter. The counter is maintained on the mutation path: incremented for every node along an insert, decremented along a delete. That keeps updates O(k) in key length and queries O(k).

Two things break it:

  1. Someone replaces the maintained counter with a recomputation: walk the subtree and count per query. Query cost goes from O(k) to O(subtree). A short prefix over a large subtree becomes the slow case.
  2. The counter drifts. A delete path that misses a decrement, or a bulk load that bypasses the insert path, leaves counts that are wrong but fast. This is the worse failure: no latency signal, just wrong answers.

Confirming which one

The discriminating test is the shape of the latency, not its magnitude.

SymptomSignatureCause
Slow querieslatency tracks subtree size: query for "a" over 1M keys slow, 20-char prefix over 3 keys fastrecompute-per-query regression
Wrong answerslatency flat, counts disagree with a full scancounter drift on a mutation path

Sample a few prefixes and compare the node counter against a full subtree scan; that separates the two in one pass.

Trade-offs

Maintaining counters costs memory per node and O(k) work per mutation. On CPython 3.11 an int is 28 bytes and a one-entry dict is 184 bytes against 64 empty, so a counter per node is a real fraction of node cost on a large trie. Recompute is the right call when the trie is rebuilt in batch, when updates dominate and prefix queries are rare, or when the memory budget is tight. Maintain when queries are frequent and the trie is mutated in place. The deciding ratio is update:query, if you query far more than you mutate, pay the per-node memory.

On-call actions

  • Confirm the signal is real before acting on the alert's stated cause.
  • If latency tracks subtree size, you have a recompute regression: roll back the deploy that introduced it, or restore the maintained counter.
  • If counts are wrong, you have drift: find the mutation path that skips the counter (bulk load, delete) and fix it, then re-derive counts with a full pass.
  • Add the assertion that would have caught it: after every mutation in tests, assert the node counter equals a recomputed subtree count.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why concurrency delays a ship date?

Answer

The 90-second version

Lead with the decision, not the mechanism. "The reservation feature ships on the 14th, not the 1st. One requirement we didn't have at kickoff drives the two weeks: the seat counter has to stay correct when all 12 API pods write to it at once. A wrong count isn't a bug we patch after launch: it's a customer seeing a seat they can't book. There are three ways to hit a date. Here's what each one costs."

Then the table, because product decides on the table, not the paragraph:

OptionShip dateWhat shipsWhat breaks
Naive read-modify-write1stfeature onlost updates above one pod; ~5 double-bookings/sec at 2,400 rps
Atomic counter (Redis INCR / Lua)14thfeature on, correct2 weeks: design, load test, migration of existing counters
Single pod1stfeature on, correctthroughput capped near 200 rps, no HA

The arithmetic that makes the delay concrete. Worked example, assumed figures: 12 pods × 200 rps = 2,400 ops/s. A read-modify-write window of 2 ms means 2,400 × 0.002 ≈ 4.8 overlapping operations per second, and each overlap is a lost update. "About five wrong counts a second" is a sentence product can repeat to their own stakeholders; "we need atomicity" is not.

What the brief has to contain, in order:

  1. The date change and the one-line reason.
  2. The consequence in customer terms: double-bookings, not lost updates.
  3. The options table with dates and risks.
  4. The scale threshold that turns the risk real ("above one pod").
  5. The decision you need, and your recommendation. Ask for a decision, not approval.

Failure modes of the brief itself, and how you catch them.

  • Mechanism instead of consequence. You say "we need a mutex"; product hears "engineering is slow" and asks to ship without it. Detect it by watching for "can we just ship it?", if that question lands, the brief failed, not the audience.
  • Burying the recommendation. Product picks the cheapest row and you own the incident. Detect it: if the meeting ends without a named option, you didn't brief, you presented.
  • Vague dates. "A couple weeks" is remembered as Friday. Every row gets a date.
  • No trigger. Without the scale threshold, product can't tell whether the risk applies to their launch. Detect it by asking them to restate what breaks and at what scale before they leave; if they can't, the brief isn't done.

Follow-ups an interviewer will push on.

"Product says ship the naive version and fix it later." You don't refuse; you price it. "Fine: we ship on the 1st with a single pod behind the load balancer, and the 14th becomes the date we turn on the other 11. Same two weeks, just spent after launch instead of before." That converts a correctness argument into a scheduling one, which is the only currency product has.

"Why can't you ship it half-correct?" Because concurrency correctness is a cliff, not a slope. A counter that's right 99.8% of the time is a counter that's wrong 4.8 times a second. There's no partial credit to ship.

"What if the load test can't reproduce it?" Then you don't have a date, you have a range, and you say so. A race you can't reproduce in a load test is a race you can't claim to have fixed: that's a third option in the table, not a footnote.

The senior move is that the brief is a decision document with a recommendation in it. You're not apologising for the delay; you're handing product three priced paths and telling them which one you'd take.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about tries in routing and dictionaries?

Answer

The experiment is a head-to-head replay, not a trie benchmark. Take the real forwarding table and the real query mix, run the trie against the two structures that could replace it: a sorted array of prefixes with binary search, and a hash map keyed by prefix length, and compare p99 lookup latency and resident memory. The falsifier is explicit: if the sorted array matches the trie's p99 within noise at the real table size, the trie is not earning its complexity and I switch. The trie's only structural claim is that lookup cost is bounded by address width (32 for IPv4, 128 for IPv6), independent of table size. So the experiment's job is to find the table size where that bound starts to bite.

Why the outcome is not obvious. A full IPv4 BGP table is on the order of 950,000 prefixes. Binary search over that is log2(950,000) ≈ 20 comparisons; a bit trie visits at most 32 nodes. The counts are comparable, so the decision turns on memory layout, not asymptotics: the sorted array is contiguous (950,000 × 8 bytes ≈ 7.6 MB), while a pointer trie chases nodes across the heap. The asymptotic story says trie; the constant-factor story may say array.

The alternative's real cost. A per-length hash map is the tempting simple structure, and its worst case is visible:

Python
# Python 3.12 — hash by prefix length instead of a trie.
def lookup(dst, by_len):
    for length in range(32, -1, -1):
        key = (dst >> (32 - length), length) if length else (0, 0)
        if key in by_len:
            return by_len[key]
    return None

Trace dst = 10.1.2.5 = 0x0A010205 against rules /8→A, /16→B, /24→C: probes at lengths 32, 31, …, 24 all miss, then length 24 hits C. 9 probes. If the table held only a /8, the same address costs 25 probes. So the hash map's cost scales with the gap between the address and the longest matching prefix, which is exactly the distribution you must measure.

Dictionaries are a different falsifier. For autocomplete and prefix search the trie's advantage is ordered traversal and prefix enumeration, not lookup. If the real operation mix is mostly exact-match (say 95% exact, 5% prefix), a hash map for exact plus a sorted array for the prefix range beats a trie on both memory and p99. The experiment: instrument the actual call mix, then measure memory per key and p99 for each structure. If exact-match dominates, the trie is the wrong tool.

Failure modes and detection. The trie's failure is memory blow-up under a large, sparse key set: detect it as RSS growth per million keys and node count versus key count (a healthy path-compressed trie stays within a small multiple of key count; a naive trie can be 10×). The array's failure is insertion cost: rebuilding a sorted array on every route update is O(n) per update, so a table with high churn (BGP updates arrive in bursts) makes the array the wrong choice even if lookups tie. Detect it as update-latency p99 and rebuild frequency. The hash map's failure is the probe chain above: detect it as probes-per-lookup in the trace.

When the trie is right. Bounded lookup independent of table size, ordered traversal, and cheap longest-prefix semantics. When it is wrong: small tables (a few hundred rules. A linear scan wins), exact-match-only workloads, or write-heavy tables where a sorted array's rebuild cost dominates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites testing a trie but cannot apply it?

Answer

The question

"Here's a trie with insert, search and delete. I insert app, then apple, then delete apple. What does search("app") return, and what single test would you add to catch a delete that gets this wrong?"

That is the whole probe. It takes three minutes, and it cannot be answered by reciting "test prefixes and the empty string": the candidate has to name the input pair, predict the output, and point at the node where the bug lives.

What a strong candidate says

search("app") returns true. delete("apple") clears the end-of-key flag on the e node and prunes upward, but it must stop at the second p node, because that node still carries the end flag for app. The test is: insert both, delete the longer, assert search("app") is still true, and assert it by searching, not by inspecting the tree, so the test survives a refactor.

Then they volunteer the empty key: insert("") sets the root's end flag, search("") reads it, delete("") clears it, and the root is the one node whose flag is easy to forget because it has no incoming edge.

The trace that decides it

Python
class Node:
    __slots__ = ("children", "end")
    def __init__(self):
        self.children = {}
        self.end = False

class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, key):
        n = self.root
        for ch in key:
            n = n.children.setdefault(ch, Node())
        n.end = True

    def search(self, key):
        n = self.root
        for ch in key:
            if ch not in n.children:
                return False
            n = n.children[ch]
        return n.end

    def delete(self, key):
        def rec(n, i):
            if i == len(key):
                n.end = False
            else:
                child = n.children.get(key[i])
                if child is None:
                    return False
                if rec(child, i + 1):
                    del n.children[key[i]]
            return not n.children and not n.end
        rec(self.root, 0)

Trace of insert("app"); insert("apple"); delete("apple"):

  • After the inserts the path is root -> a -> p -> p(end) -> l -> e(end).
  • delete("apple") descends to the e node, sets end = False, and returns True (no children, no end flag), so l drops e.
  • The l node now has no children and no end flag, returns True, so the second p drops l.
  • The second p node has no children but end is still True for app, so it returns False and pruning stops.
  • search("app") walks to that node and returns True.

A delete that prunes unconditionally deletes the p node too, and search("app") returns False. That is the failure the test catches.

Follow-ups

  • "Now delete app as well. What happens to the a node?": checks they know pruning continues to the root only while no node on the path has an end flag or another child.
  • "Your suite has 10,000 keys, all eight characters long. What does it miss?": same-length keys never produce a prefix pair, so the flag logic is never exercised.
  • "Unit test or property test?": a property test over random key sets with a prefix relation is the honest answer; the hand-written pair is the minimum.

Why this probe and not the alternatives

Asking them to implement a trie from scratch measures recall of a structure they may have memorised; a candidate can produce a working implementation and still not know which input breaks it. Asking for the complexity of search, O(m) in the key length, is trivia. This probe asks for the one thing recitation cannot fake: the input that separates a correct delete from a plausible one.

Failure modes of the probe

If the candidate has never seen a trie, this measures exposure, not skill: describe the structure in one line first ("each node holds a map of characters to children and a flag for whether a key ends here"). If they freeze, hand them the input pair and ask only for the predicted output; that still separates the two groups. And do not accept "I'd test edge cases": ask for the case.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document when not to use a trie so the next owner can operate it?

Answer

The 90-second answer

Don't document the trie; document the invariant that makes it correct. A trie is only justified by a query pattern, prefix scan or ordered iteration, so the record should say which pattern, how often it actually occurs, and what measurement would show it has gone away. Put it in an ADR next to the code, leave a five-line pointer at the trie's definition, and back the tripwire with a metric and an alert rather than a review date. If the invariant can't be stated in one sentence, the trie probably shouldn't be there.

The artefact

An ADR with four fields and nothing else:

# ADR-014: prefix index over object keys
# Decision: trie keyed on object-key strings, built at startup.
# Invariant: ListPrefix(prefix) is on the read path. Measured 2025-03-01..03-31:
#   38% of reads, p50 1.2 ms, p99 9 ms at 4.1M keys.   [illustrative numbers]
# Rejected: sorted array + binary search (O(log n + m) scan, but O(n) rebuild
#   per write); hash map (no prefix scan at all).
# Tripwire: ListPrefix < 5% of reads for 14 consecutive days -> replace with a
#   dict, delete the index. Alert: index/query_mix. Owner: storage.

The tripwire is what makes it operational. A date ("revisit Q3") is not a tripwire; a metric with a threshold and an alert is. The comment at the trie's definition should be one line pointing at the ADR, so the next owner finds it from the code rather than from a wiki search.

Choosing the alternatives

Query mixRight structureWhy not the trie
100% exact matchhash mapO(1) lookup, no per-character nodes
Prefix scan + exact matchtriehash map can't scan by prefix
Ranked full-textinverted indextrie gives no term weighting
Ordered iteration onlysorted array / B-treeO(log n) seek, cache-friendly, no 16-way fan-out

k = key length, n = keys. The trie's advantage is that a prefix scan is O(k + m) for m matches, where a hash map has to touch all n keys.

Worked example: what the tripwire is protecting

100,000 random 32-char hex keys (UUIDs without dashes), CPython 3.11 on 64-bit. Random keys share almost no prefixes, which is the worst case for a trie:

  • Nodes: levels 0-4 hold 1+16+256+4096+65536 ≈ 70k; each key then owns a 28-node tail, 100,000 × 28 = 2.8M. Total ≈ 2.9M nodes.
  • Per node: a one-child dict is 184 B in 3.11 (240 B in 3.6-3.10), plus ~48 B for a __slots__ node object → ~232 B.
  • Trie: 2.9M × 232 B ≈ 670 MB.
  • dict: 100k entries → 1 MB index table + 2.4 MB entry array + 100k × 81 B key strings ≈ 11.6 MB.

Roughly 58× the memory, and every exact-match lookup now walks 32 pointers instead of one hash. If the prefix queries stop, that is the bill.

Failure modes and detection

  • Kept out of inertia: 670 MB resident for a workload that never scans a prefix. Detect with the query-mix metric and RSS; the alert fires before anyone notices by hand.
  • Replaced with a dict: prefix scans silently return nothing, or the caller falls back to a full scan. Detect with a test asserting ListPrefix returns every matching key, plus a p99 alert on the prefix endpoint.
  • Doc rot: the ADR is written and never read. Detect by making the tripwire an alert, not a calendar entry.

Curated: · Written: · Reviewed:

Difficulty: Medium