String Algorithms and Pattern Matching Questions
Advanced string algorithms for coding interviews: substring search (naive baseline, KMP including streaming use, Rabin-Karp with collision-resistant hashing, Z-algorithm, Boyer-Moore), multiple-pattern matching (Aho-Corasick, including large automata and updates under memory limits), suffix arrays (doubling construction, binary-search queries, Kasai LCP), suffix trees (Ukkonen) and suffix automata, repeated, common and distinct-substring problems (suffix array plus LCP, binary search on length with a rolling hash), the Burrows-Wheeler transform and FM-index, palindromic structures (Manacher), minimal string rotation (Booth), approximate matching beyond the textbook recurrence (banded and bit-parallel edit distance, matching with k mismatches), wildcard and regular-expression matching including backtracking engines, catastrophic backtracking and its mitigations, and string applications built on a trie (multi-pattern dictionaries, autocomplete and prefix search at scale). Also covers Unicode-aware matching and normalization, and adversarial inputs such as hash collisions and the cost of each defence. Boundary: introductory string manipulation, the trie as a data structure, edit-distance and subsequence recurrences, hash-map counting problems, generic data cleaning, NLP pipelines and test-plan design are covered elsewhere.
Explain greedy vs lazy quantifiers in regular expressions and give a concrete example where greedy matching produces a different result from lazy matching. Define catastrophic backtracking, show a regex example that can trigger it, and describe how to mitigate the issue.
Sample Answer
The idea in plain words
A quantifier says how many times the thing before it may repeat: * (zero or more), + (one or more), ? (zero or one), {m,n} (between m and n). Most regex engines in languages like Python, Java, JavaScript and Perl are backtracking engines: they try one way to match, and when a later part of the pattern fails they undo (backtrack) their last choice and try the next option.
- A greedy quantifier (
+,*) first takes as much text as it can, then gives characters back one at a time if the rest of the pattern fails. - A lazy quantifier (
+?,*?) first takes as little as it can (the minimum), then takes one more character at a time if the rest fails.
The overall match succeeds on both in the same situations, but they can choose different substrings when several matches are possible. Catastrophic backtracking is the second half of the question: when a pattern offers so many ways to split the input that the engine tries an exponential number of them before giving up.
Greedy vs lazy, with a concrete example
Take the text <b>bold</b> and <i>italic</i> and want the HTML tags. Greedy <.+> starts at the first <, lets .+ (any characters, one or more) swallow to the end of the string, finds nothing after it, and gives back one character: the last > now matches. Lazy <.+?> takes one character after <, sees > next and stops. A third pattern, <[^>]+> (any run of characters that are not >), reaches the same answer as the lazy one without any backtracking, because it can never run past a >.
The same program counts how many lengths of the .+ part a hand-written backtracker tries. On <a> followed by ten x characters, greedy tries 12 lengths before it finds the > at position 2, lazy tries 1:
import re
html = "<b>bold</b> and <i>italic</i>"
print("greedy :", re.findall(r"<.+>", html))
print("lazy :", re.findall(r"<.+?>", html))
print("negated :", re.findall(r"<[^>]+>", html))
def dot_plus_then_gt(text, lazy):
"""Backtracker for '<' + '.+' + '>' anchored at index 0.
Returns the match (or None) and how many lengths k of the '.+' part were tried."""
if not text.startswith("<"):
return None, 0
longest = len(text) - 1
order = range(1, longest + 1) if lazy else range(longest, 0, -1)
tried = 0
for k in order: # '.+' takes k characters, then '>' must follow
tried += 1
if 1 + k < len(text) and text[1 + k] == ">":
return text[: 2 + k], tried
return None, tried
for text in (html, "<a>" + "x" * 10):
for lazy in (False, True):
print("lazy " if lazy else "greedy", repr(text[:14]), dot_plus_then_gt(text, lazy))
# Catastrophic backtracking: count the attempts of a backtracker for ^(a+)+$
calls = 0
visited = []
def nested(text, pos):
"""After one or more iterations of (a+) ended at pos: finish at the end or try another iteration."""
global calls
calls += 1
visited.append(pos)
if pos == len(text):
return True
run = 0
while pos + run < len(text) and text[pos + run] == "a":
run += 1
for take in range(run, 0, -1): # greedy: longest a-run first, then shorter
if nested(text, pos + take):
return True
return False
print("n attempts for ^(a+)+$ on 'a'*n + 'b'")
for n in range(10, 23, 3):
calls = 0
nested("a" * n + "b", 0)
print(f"{n:2d} {calls}")
calls = 0
visited.clear()
nested("aaab", 0)
print("n=3: positions visited", visited, "-> calls", calls)
print("a+a on 'aaa':", bool(re.fullmatch(r"a+a", "aaa")))
print("a++a on 'aaa':", bool(re.fullmatch(r"a++a", "aaa")))
print("fixed with atomic group :", re.fullmatch(r"(?>a+)+", "a" * 5000 + "b"))
print("fixed with possessive :", re.fullmatch(r"a++", "a" * 5000 + "b"))
print("fixed by simplifying :", re.fullmatch(r"a+", "a" * 5000 + "b"))
print("still matches good input:", bool(re.fullmatch(r"(?>a+)+", "a" * 5000)))
Output:
greedy : ['<b>bold</b> and <i>italic</i>']
lazy : ['<b>', '</b>', '<i>', '</i>']
negated : ['<b>', '</b>', '<i>', '</i>']
greedy '<b>bold</b> an' ('<b>bold</b> and <i>italic</i>', 2)
lazy '<b>bold</b> an' ('<b>', 1)
greedy '<a>xxxxxxxxxx' ('<a>', 12)
lazy '<a>xxxxxxxxxx' ('<a>', 1)
n attempts for ^(a+)+$ on 'a'*n + 'b'
10 1024
13 8192
16 65536
19 524288
22 4194304
n=3: positions visited [0, 3, 2, 3, 1, 3, 2, 3] -> calls 8
a+a on 'aaa': True
a++a on 'aaa': False
fixed with atomic group : None
fixed with possessive : None
fixed by simplifying : None
still matches good input: True
The first three lines are the result of each pattern: greedy returns one long match that spans both tags, lazy and the negated class return four separate tags. Rule of thumb: use lazy when you want "the shortest thing up to the next delimiter", and prefer a negated character class ([^>], [^"]) when the delimiter is a single character, since it is both clear and cheap.
What catastrophic backtracking is
It is the case where the number of ways the engine can divide the input between parts of the pattern grows exponentially with the input length, and the input fails to match at the very end, so every one of those ways gets tried. The standard trigger is a nested quantifier: a repeat applied to a group that itself repeats, like ^(a+)+$.
Take the input aaaa...ab. The pattern needs only as up to the end of the string ($), but the final b ruins every attempt. The inner a+ can take 1, 2, ... n characters, and the outer + can then repeat the group on whatever is left. A run of n letters can be cut into groups in 2^(n-1) ways (put a cut or no cut between each pair of neighbours), and a backtracking engine tries them all before reporting failure. The nested function counts its calls, and its count is 2^n, one doubling more than the 2^(n-1) complete ways, because it also counts the partial ways on the road to them. A call at position p exists for every way of cutting the first p letters (2^(p-1) ways for p >= 1, one way for p = 0), so the total is 1 + 2^0 + 2^1 + ... + 2^(n-1) = 2^n. For aaab (n = 3) the output line n=3: positions visited [0, 3, 2, 3, 1, 3, 2, 3] -> calls 8 shows it: four of the calls are at position 3 (the four complete cuts aaa, aa|a, a|aa, a|a|a, each stopping at the b, which $ cannot accept), and the other four are the partial calls at positions 0, 2, 1 and 2. For n = 10 that is 512 complete ways and 1024 calls. The table of attempts for a repeated n times followed by b: 1024 for n = 10, 8192 for 13, 65536 for 16, 524288 for 19 and 4194304 for 22. Each extra a doubles the work, so a 30-character input costs about a thousand times more than a 20-character one, and a 50-character input is out of reach.
Another classic shape is ^(a|aa)+$: each run of as can be split into pieces of one or two characters in many ways. The common feature is ambiguity: the same text can be matched by the pattern in many different ways.
Why it matters: ReDoS
ReDoS (regular-expression denial of service) is an attack where a user submits a short string crafted to hit this behaviour, so a single request pins a CPU core. It affects input-validation regexes (emails, URLs, usernames) running on a user-supplied string.
Mitigations
- Remove the ambiguity. Rewrite
^(a+)+$as^a+$. Make alternatives start with different characters. Keep adjacent parts from matching the same characters. - Use atomic groups or possessive quantifiers (Python 3.11 and later:
(?>...)anda++). These forbid giving characters back (oncea++has taken a run ofas, the engine never returns any of them to let the rest of the pattern try), so there is nothing to try. The effect on a result:a+amatchesaaa(thea+gives one character back for the finala), whilea++adoes not (the output shows True and False), sincea++keeps all three. The last four lines of the output show(?>a+)+,a++anda+all failing quickly on 5000as followed byb, while(?>a+)+still matches a clean string ofas. The cost: a possessive pattern can fail to match inputs a normal backtracking one would accept, since it refuses to give back, so test it. - Use a linear-time engine for untrusted patterns or inputs, such as RE2 (a regular-expression library from Google designed to run in time linear in the input) and Go's
regexp, which uses the same approach. They simulate all alternatives at once, so time is proportional to the input length times the pattern size, at the cost of not supporting back-references (a\1that must match the same text an earlier group captured) and look-around (conditions such as "followed by x" that check the text next to the current position without consuming it). - Bound the input and the time. Cap the input length before matching, run matching with a time limit or in a separate worker you can kill, and review regexes with a ReDoS linter (a tool that analyses a pattern and flags nested or overlapping repeats that can blow up).
Complexity and edge cases
- Greedy and lazy versions of a simple pattern like
<.+>cost O(n) per starting position, so O(n^2) over a text with many starts in the worst case (a<with no>anywhere is the example). - The nested pattern costs O(2^n) on a failing input of n letters; the atomic and rewritten versions cost O(n).
- Edge cases: an empty match is allowed by
*but not+; lazy and greedy produce the same match when only one match is possible;.does not match a newline unless a flag is set, which changes what<.+>spans in multi-line HTML. - Common mistake: believing lazy quantifiers prevent catastrophic backtracking. They only change the order in which the options are tried; on a failing input every option is still tried.
Running the code
# save the listing as quantifiers.py (Python 3.12, standard library only)
python quantifiers.py
You must compute the edit distance between two very long strings, but you expect the true distance k to be small. How would you get the cost down to roughly O(k * n) time, and what would you store? Walk through the idea and sketch the code.
Sample Answer
The idea in plain words
Edit distance (Levenshtein distance) is the minimum number of single-character insertions, deletions and substitutions that turn string a into string b. The textbook table D[i][j] (the distance between the first i characters of a and the first j of b) has n x m cells, which for two 100,000-character strings is 10 billion cells.
The insight: an alignment is a path through that table from the top-left to the bottom-right. Every insertion or deletion moves the path one diagonal away from the main diagonal (where i = j) and costs 1. So a path of total cost at most k never leaves the band where |i - j| <= k. If you expect the answer to be small, compute only that band, about (2k + 1) cells per row instead of m, for O(k * n) time.
The recurrence, with a tiny table
Each cell is the cheapest of three moves:
- Delete
a[i-1]:D[i-1][j] + 1(the first i-1 characters ofaalready match the first j ofb; drop one more character ofa). - Insert
b[j-1]:D[i][j-1] + 1(the first i ofamatch the first j-1 ofb; add the missing character ofb). - Match or substitute:
D[i-1][j-1]plus 0 ifa[i-1] == b[j-1], else plus 1.
The first row and column are D[0][j] = j and D[i][0] = i (turning a string into an empty one, or the reverse, costs its length). By hand for kitten to sitting: D[1][1] compares k with s, a mismatch, so it is min(D[0][1] + 1, D[1][0] + 1, D[0][0] + 1) = min(2, 2, 1) = 1. D[1][2] (k against si) is min(D[0][2] + 1, D[1][1] + 1, D[0][1] + 1) = min(3, 2, 2) = 2. D[2][2] (ki against si) has i == i, so it is D[1][1] + 0 = 1. The program prints the whole table; the band |i - j| <= 3 is the part that is not a dot.
The brute force and why it is not enough
The full table costs O(n * m) time. It can be done in O(min(n, m)) memory by keeping two rows, but the time is still quadratic. When the true distance d is small (two versions of the same file, two reads of the same genome region), almost all of that work fills in cells far from the diagonal that cannot be on an optimal path.
The catch: you do not know d in advance
The band width k must be at least the true distance, otherwise the band may cut off the optimal path. Two facts handle that:
- If
abs(len(a) - len(b)) > kthe answer is certainly more than k (each length difference needs at least one insertion or deletion), so such a band is rejected immediately. - Inside a band of half-width k, a returned value that is at most k is exact, and a value above k means "the distance is more than k". Any value above k is clamped to k + 1, which also keeps the numbers small.
So double the band: try k = 1, 2, 4, 8, ..., stop at the first k whose result is at most k. The pass that succeeds has k < 2d (for d >= 1), because the previous pass with k/2 failed. For d = 12 the bands tried are 1, 2, 4, 8 (all too small) and 16 (which is below 2 * 12 = 24). Each pass costs O(k * n), so the costs are n, 2n, 4n, 8n, 16n: a geometric series, where each term is double the one before, so the whole sum is less than twice the last term. The total is dominated by the last pass: O(d * n) overall, within a small constant of one pass with the perfect k.
What to store
Only the band. For each row i keep the cells with i - k <= j <= i + k. To get the distance you need only the previous row, so memory is O(k). If you also need the alignment itself (which edits to make), keep all rows of the band for O(k * n) memory, or recompute with Hirschberg's divide-and-conquer (find which cell of the middle row the best path passes through using only two rows, then solve the two halves separately) to get O(k) memory at about twice the time.
Code
def full_edit_distance(a, b):
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] != b[j - 1]))
prev = cur
return prev[-1]
def show_table(a, b, k):
"""Print the full table D[i][j]; cells outside the band |i - j| <= k print as '.'."""
n, m = len(a), len(b)
D = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1):
for j in range(m + 1):
if i == 0 or j == 0:
D[i][j] = i + j
else:
D[i][j] = min(D[i - 1][j] + 1, D[i][j - 1] + 1, D[i - 1][j - 1] + (a[i - 1] != b[j - 1]))
print(" " + " ".join(["-"] + list(b)))
for i in range(n + 1):
row = [str(D[i][j]) if abs(i - j) <= k else "." for j in range(m + 1)]
print(f" {a[i - 1] if i else '-'} " + " ".join(row))
edits, i, j = [], n, m
while i or j:
if i and j and D[i][j] == D[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
if a[i - 1] != b[j - 1]:
edits.append(f"replace {a[i - 1]!r} with {b[j - 1]!r}")
i, j = i - 1, j - 1
elif i and D[i][j] == D[i - 1][j] + 1:
edits.append(f"delete {a[i - 1]!r}")
i -= 1
else:
edits.append(f"insert {b[j - 1]!r}")
j -= 1
print(" edits (last position first):", "; ".join(edits))
def banded_edit_distance(a, b, k):
"""Edit distance if it is <= k, else None. Only cells with |i - j| <= k are computed."""
n, m = len(a), len(b)
if abs(n - m) > k:
return None, 0
INF = k + 1 # any value above k means "too far"
prev = {j: j for j in range(0, min(m, k) + 1)} # row 0
cells = len(prev)
for i in range(1, n + 1):
lo, hi = max(0, i - k), min(m, i + k)
cur = {}
for j in range(lo, hi + 1):
if j == 0:
best = i
else:
best = min(
prev.get(j, INF) + 1, # delete a[i-1]
cur.get(j - 1, INF) + 1, # insert b[j-1]
prev.get(j - 1, INF) + (a[i - 1] != b[j - 1]), # match / substitute
)
cur[j] = min(best, INF)
cells += len(cur)
prev = cur
d = prev.get(m, INF)
return (d if d <= k else None), cells
def edit_distance_doubling(a, b, verbose=False):
"""Try k = 1, 2, 4, ... until the banded answer fits inside the band."""
k, total_cells = 1, 0
while True:
d, cells = banded_edit_distance(a, b, k)
total_cells += cells
if verbose:
print(f" band k={k}: cells={cells}, result={d}")
if d is not None:
return d, k, total_cells
k *= 2
if __name__ == "__main__":
print("table for kitten -> sitting, cells with |i - j| <= 3 shown (band k = 3):")
show_table("kitten", "sitting", 3)
print(banded_edit_distance("kitten", "sitting", 3))
print(banded_edit_distance("kitten", "sitting", 2))
print(banded_edit_distance("ab", "abcdef", 2)) # length gap 4 > 2: rejected before any cell is computed
print(edit_distance_doubling("", "abcde")) # bands 1, 2, 4 are rejected for free; k = 8 answers
import random
random.seed(1)
n = 2000
a = "".join(random.choice("ACGT") for _ in range(n))
b = list(a)
for pos in random.sample(range(n), 12):
b[pos] = random.choice("ACGT")
del b[500]; b.insert(1200, "G")
b = "".join(b)
d, k, cells = edit_distance_doubling(a, b, verbose=True)
print("distance", d, "final band", k, "cells computed", cells, "full table cells", (n + 1) * (len(b) + 1))
print("matches full DP:", d == full_edit_distance(a, b))
Run in a python:3.12 container, it prints:
table for kitten -> sitting, cells with |i - j| <= 3 shown (band k = 3):
- s i t t i n g
- 0 1 2 3 . . . .
k 1 1 2 3 4 . . .
i 2 2 1 2 3 4 . .
t 3 3 2 1 2 3 4 .
t . 4 3 2 1 2 3 4
e . . 4 3 2 2 3 4
n . . . 4 3 3 2 3
edits (last position first): insert 'g'; replace 'e' with 'i'; replace 'k' with 's'
(3, 40)
(None, 31)
(None, 0)
(5, 8, 6)
band k=1: cells=6001, result=None
band k=2: cells=9999, result=None
band k=4: cells=17989, result=None
band k=8: cells=33945, result=None
band k=16: cells=65761, result=12
distance 12 final band 16 cells computed 133695 full table cells 4004001
matches full DP: True
Worked trace
- "kitten" to "sitting" has distance 3, and the bottom-right cell of the printed table is 3. The edit list read from the table is: replace
kwiths, replaceewithi, insertg. The band with k = 3 is every cell where the row and column numbers differ by at most 3: the printed table shows 4, 5, 6, 7, 7, 6 and 5 cells in its seven rows, 40 in total, against the 56 cells of the full 7 by 8 table. With band k = 3 the function returns 3 after computing those 40 cells. With k = 2 it returnsNoneafter 31 cells, correctly reporting "more than 2". The next two printed lines show the length-difference check: "ab" against "abcdef" with k = 2 returns(None, 0)with no cell computed, and "" against "abcde" is rejected for k = 1, 2 and 4 at no cost, then answers 5 with k = 8 after 6 cells. - The 2,000-character DNA-like pair is built by applying up to 12 random substitutions (a random pick can repeat the same letter), one deletion and one insertion; the program reports the actual distance, 12. The doubling loop tries bands 1, 2, 4 and 8, each returning
None, then band 16 returns 12. The cell counts per pass are 6,001; 9,999; 17,989; 33,945 and 65,761, adding up to 133,695. - The full table would have 4,004,001 cells, so the banded search computed about 30 times fewer (4,004,001 / 133,695 = 29.9). The final line confirms the answer equals the full dynamic-programming result.
Complexity
- Time: each pass with half-width k computes at most 2k + 1 cells per row, so O(k * n). With doubling the passes cost O(1 * n), O(2 * n), O(4 * n) and so on; the sum is below twice the last pass, and the last pass has k < 2d, so the total is O(d * n).
- Space: the code keeps two rows of at most 2k + 1 entries, so O(d) at the end (a dictionary per row here; in a faster implementation two preallocated arrays of length 2k + 1).
- Going further: a typical interview needs the banded table with doubling; the diagonal-transition methods are deeper material. Landau and Vishkin's method (O(n + k^2) with a constant-time longest-common-extension query, that is, a precomputed answer to "how far do these two suffixes agree starting here?") and Myers' O(ND) difference algorithm (which counts insertions and deletions only, not substitutions) do not fill cells one by one. For each number of edits e and each diagonal they record only the furthest row reachable, sliding along matching characters for free, which beats the O(k * n) banded approach when d is small.
Edge cases and common mistakes
- Identical strings: d = 0 is found with k = 1 on the first pass.
- One or both strings empty: the distance is the other length; the length-difference check rejects small bands until k reaches it.
- Skipping the length-difference check: the answer stays correct, because the bottom-right cell then lies outside the band and reads as
k + 1, which becomesNone; but the code first fills the whole band for nothing (12 cells instead of 0 for "ab" against "abcdef" with k = 2, and a full pass of about n x (2k + 1) cells on long strings). The check is an early exit, not a correctness guard. - Not capping values: anything above k is never needed, so cap at k + 1; that also makes the treatment of out-of-band neighbours consistent.
- Reading out-of-band cells: neighbours outside the band are treated as "greater than k" (the code uses
k + 1throughprev.get(j, INF)), never as 0. - Recomputing each pass from scratch: every pass recomputes its whole band; reusing the narrower band's rows is possible but not worth the complexity because the work is a geometric series.
- Thinking an answer of
Noneis an error: it means the distance exceeds the band and the loop should double.
Verification
The banded function was compared with the full dynamic program on 3,000 random binary-alphabet string pairs (lengths 0 to 9) for every band from 0 to 5, and the doubling wrapper was compared with the full result on the same pairs. All agreed.
Running the code
Save the listing as banded_edit_distance.py (Python 3.12, standard library only), then: python banded_edit_distance.py
Explain Unicode normalization forms (NFC, NFD, NFKC, NFKD) and why normalization matters for reliable string matching across data sources. Describe how you would design ingestion pipelines to normalize user-generated text for search and matching purposes.
Sample Answer
The idea in plain words
Unicode gives some characters more than one valid spelling. The letter e with an acute accent can be one code point (a code point is one numbered entry of the Unicode table, written U+00E9) or two: e followed by a combining acute accent (U+0065 U+0301). Both draw the same glyph (the picture of the character that appears on screen), with the accent drawn by a combining mark, a code point that attaches itself to the letter before it instead of standing alone. But a program comparing them byte by byte or code point by code point says they differ. Normalization rewrites text into one agreed spelling so that text that should be the same compares as the same. Matching text from different sources (a database, a browser form, a PDF, a phone keyboard) without it gives silent misses: the search for "café" finds nothing, though the user can see it on the screen.
The two kinds of equivalence and the four forms
- Canonical equivalence: sequences that mean exactly the same thing and should look the same (
U+00E9andU+0065 U+0301; also the Angstrom signU+212Band the Swedish letterU+00C5). - Compatibility equivalence: sequences that are similar but differ in format or style (the
filigatureU+FB01and the two lettersfi; a full-widthAand a plainA; the superscript²and2). Collapsing these loses information, so it is a lossy step.
| Form | Name | What it does | Lossy? |
|---|---|---|---|
| NFD | Normalization Form Canonical Decomposition | splits composed characters into base letter plus combining marks, and puts the marks in a fixed order | no |
| NFC | Normalization Form Canonical Composition | NFD, then re-joins into composed characters where one exists | no |
| NFKD | Normalization Form Compatibility Decomposition | compatibility mapping, then decomposes | yes |
| NFKC | Normalization Form Compatibility Composition | compatibility mapping, then composes | yes |
NFC is the usual form for storage and for text exchanged on the web. NFKC is the form to use when building a matching key. The program below shows all of it on real data. Every non-ASCII character in it is written as a \uXXXX escape (for example caf\u00e9 for the one-code-point spelling and cafe\u0301 for the two-code-point spelling), so the listing shows which spelling each line uses; the lines of output that carry the core point are the first five (the café pair under all four forms); the later lines are further cases of the same two ideas (canonical vs compatibility) plus pipeline facts used below.
import unicodedata as ud
def cps(s: str) -> str:
return " ".join(f"U+{ord(c):04X}" for c in s)
def search_key(text: str) -> str:
"""Matching key: compatibility-normalise, fold case, drop accents."""
folded = ud.normalize("NFKC", text).casefold()
decomposed = ud.normalize("NFD", folded)
stripped = "".join(c for c in decomposed if ud.category(c) != "Mn")
return ud.normalize("NFC", stripped)
one = "caf\u00e9" # e-acute as a single code point
two = "cafe\u0301" # e followed by a combining acute accent
print("same on screen, equal in Python?", one == two, "| lengths", len(one), len(two))
for form in ("NFC", "NFD", "NFKC", "NFKD"):
print(f"{form:4s} one==two: {ud.normalize(form, one) == ud.normalize(form, two)}"
f" one -> {cps(ud.normalize(form, one)[3:])}")
print()
samples = {
"ligature fi": "\ufb01le", # U+FB01 LATIN SMALL LIGATURE FI + "le"
"circled one": "\u2460",
"superscript two": "x\u00b2",
"full-width A": "\uff21BC",
"angstrom sign": "\u212b", # U+212B ANGSTROM SIGN (canonically equal to U+00C5)
"Hangul syllable": "\ud55c", # U+D55C, one precomposed Korean syllable
}
for name, s in samples.items():
print(f"{name:16s} NFC={cps(ud.normalize('NFC', s)):28s} NFKC={cps(ud.normalize('NFKC', s))}")
dot_then_acute, acute_then_dot = "a\u0323\u0301", "a\u0301\u0323"
print("marks in either order equal after NFC?", ud.normalize("NFC", dot_then_acute) == ud.normalize("NFC", acute_then_dot))
print("Hangul NFD has", len(ud.normalize("NFD", samples["Hangul syllable"])), "code points")
print()
print("search_key('Cafe\\u0301') == search_key('CAF\\u00c9'):", search_key("Cafe\u0301") == search_key("CAF\u00c9"))
print("German sharp s:", repr("Stra\u00dfe".casefold()), "| Spanish n-tilde key:", repr(search_key("ni\u00f1o")))
print("Latin a vs Cyrillic a (U+0430) equal after NFKC?", ud.normalize("NFKC", "a") == ud.normalize("NFKC", "\u0430"))
print("Devanagari ku (U+0915 U+0941) and ka (U+0915) share a key:", search_key("\u0915\u0941") == search_key("\u0915"))
widest = max(range(0x110000), key=lambda cp: len(ud.normalize("NFKC", chr(cp))))
print(f"widest NFKC expansion: U+{widest:04X} becomes {len(ud.normalize('NFKC', chr(widest)))} code points")
print("unicodedata uses Unicode", ud.unidata_version)
Output:
same on screen, equal in Python? False | lengths 4 5
NFC one==two: True one -> U+00E9
NFD one==two: True one -> U+0065 U+0301
NFKC one==two: True one -> U+00E9
NFKD one==two: True one -> U+0065 U+0301
ligature fi NFC=U+FB01 U+006C U+0065 NFKC=U+0066 U+0069 U+006C U+0065
circled one NFC=U+2460 NFKC=U+0031
superscript two NFC=U+0078 U+00B2 NFKC=U+0078 U+0032
full-width A NFC=U+FF21 U+0042 U+0043 NFKC=U+0041 U+0042 U+0043
angstrom sign NFC=U+00C5 NFKC=U+00C5
Hangul syllable NFC=U+D55C NFKC=U+D55C
marks in either order equal after NFC? True
Hangul NFD has 3 code points
search_key('Cafe\u0301') == search_key('CAF\u00c9'): True
German sharp s: 'strasse' | Spanish n-tilde key: 'nino'
Latin a vs Cyrillic a (U+0430) equal after NFKC? False
Devanagari ku (U+0915 U+0941) and ka (U+0915) share a key: True
widest NFKC expansion: U+FDFA becomes 18 code points
unicodedata uses Unicode 15.0.0
Reading the output:
caféas one code point is 4 long, the two-code-point spelling is 5 long, and they are not==. After any of the four forms they compare equal. NFC and NFKC giveU+00E9(composed), NFD and NFKD giveU+0065 U+0301.- The
filigature, the circled digit, the superscript and the full-widthAchange only under the K forms (NFKC): that is the compatibility step. NFC leaves them alone. - The Angstrom sign becomes
U+00C5under both, because the two are canonically equivalent. A Hangul syllable (a Korean letter block such as U+D55C, written as one code point) decomposes under NFD into its 3 jamo, the individual letter components, and recomposes under NFC. - Combining marks typed in a different order (
a+ dot below + acute vsa+ acute + dot below) compare equal after normalization, which is the fixed ordering NFD applies. - Normalization does not make look-alike letters from different scripts equal: Latin
aand Cyrillicаstay different. That is a security concern handled by a separate confusable check (a lookup of characters from different scripts that look alike), not by normalization. - Normalization is not case folding or accent removal. The
search_keyfunction in the listing adds those: NFKC, thencasefold()(a stronger lowercase: GermanStraßebecomesstrasse), then NFD with the combining marks dropped (Mnis the Unicode general category "Mark, nonspacing": marks that sit on a base letter. In Latin text these are accents, but the category also holds Hebrew points, Arabic vowel marks and many Indic vowel signs, so this step is only safe for Latin-script fields; the Devanagari line of the output showskuandkagetting the same key), then NFC.
Why it matters for matching
- Equality, hashing and dictionary keys compare code points, and so do database unique constraints under the usual byte-wise collations (PostgreSQL's standard collations are deterministic, which means two strings are equal only if their bytes are identical; a nondeterministic ICU collation can be declared to treat different normal forms as equal, at a performance cost and with some pattern-matching operations unavailable), so the same visible name stored twice under two spellings becomes two rows.
- Substring search,
LIKE, and every string-matching algorithm (KMP, Rabin-Karp, an Aho-Corasick automaton) match code points or bytes. A pattern written ascafplus the single code pointU+00E9will not match a text that spells the same word ascafeplusU+0301. - Length limits, truncation and slicing count code points, so a cut can land between a base letter and its mark and leave a stray accent.
Designing the ingestion pipeline
The two steps that carry the design are step 3 (store the original and a separate search key) and step 4 (one function, used everywhere). The others are refinements that matter once those two are in place.
- Decode strictly. Reject or replace invalid UTF-8 at the edge; normalization works on text, not bytes.
- Cap the size before and after. The compatibility forms can expand text: the widest single expansion in this Unicode version is
U+FDFA, which becomes 18 code points under NFKC. Check the length limit on the raw input and again on the normalized output. - Store two things. Keep the original string for display and audit (stored in NFC, which does not change what it means; keep the raw bytes as well if an audit must show exactly what was typed), and keep a derived search key (NFKC, case-folded, accents optionally stripped) in its own column or index field. Matching and unique constraints use the key. This keeps the lossy step reversible.
- Use one function everywhere. The same
search_keyruns at index time, at query time and in any batch job. A query that is normalized differently from the index silently misses. - Decide accent folding per language. Dropping marks makes
niñoequalnino, which is helpful for typing on a keyboard without accents but wrong where the accent changes the word (Spanishñ, Germanüin some contexts). Make it a field-level setting, or index both forms. Apply the mark-stripping step only to Latin-script fields; in other scripts the marks are often vowels or letters, and stripping them merges different words. - Version the pipeline. Store a
normalization_versionnext to the key. Unicode adds characters and the normalization data it ships changes (this run used Unicode 15.0.0), so a new version of the runtime library can produce different keys for new characters. When the version changes, re-key in a background job. Already-normalized text stays stable across Unicode versions under the standard's normalization stability policy (once a string made only of characters assigned in that version is normalized, a later Unicode version will not change its normalized form), which is why NFC storage is safe. - Test with fixtures. Keep a list of pairs that must match (composed vs decomposed, ligature, full-width, mark order) and pairs that must not (Latin vs Cyrillic
a,ßvssif your product treats them as different). - Handle identifiers and security separately. For usernames and URLs, normalize, then apply a confusable-character check and restrict allowed scripts.
Trade-offs and mistakes
- NFKC for storage destroys information (
²becomes2,①becomes1), so use it only for keys and keep the original. - Normalizing only one side of a comparison is the most common bug.
- Treating
len()as the number of visible characters: a user-perceived character (a grapheme cluster) can be several code points even after NFC (an emoji with a skin-tone modifier, or a letter with a mark that has no precomposed form). Use a grapheme-aware library for truncation and cursor movement. - Assuming a case-insensitive match is
lower(): usecasefold().
Running the code
# save the listing as normalize_demo.py (Python 3.12, standard library only)
python normalize_demo.py
Describe the bad-character heuristic used by the Boyer–Moore algorithm. Explain how to build the bad-character table, how to compute shifts on mismatch, and why Boyer–Moore can be sublinear on average for typical natural-language text.
Sample Answer
The idea in plain words
Normal substring search lines the pattern up under the text and compares left to right. Boyer-Moore compares right to left inside the alignment, and on the first mismatch it asks one question about the text character that caused it: "where is this character in the pattern?" If the character is not in the pattern at all, no alignment that overlaps it can match, so the whole pattern jumps past it. That jump, based on the offending text character (the "bad character"), is the bad-character heuristic. Because it can skip up to m text characters per mismatch, the algorithm often reads fewer than n characters of the text. That is what sublinear means here: fewer than n character comparisons for a text of n characters, even though KMP and the Z algorithm read every text character at least once.
Building the bad-character table
Record, for every character, the index of its rightmost occurrence in the pattern. For "EXAMPLE" the table is {E: 6, X: 1, A: 2, M: 3, P: 4, L: 5}. E is stored at 6 (the last E), not 0, because the rightmost occurrence gives the smallest safe shift. A character not in the table counts as -1. Building it is one pass over the pattern, O(m) time and O(distinct characters) space.
Computing the shift on a mismatch
With the pattern aligned at text index s, suppose the comparison from the right fails at pattern index j, where the text holds character c at s + j. Slide the pattern so that the rightmost c in the pattern lines up under that text character:
shift=max(1,j−last[c])- c not in the pattern: last[c] = -1, so the shift is j + 1, and the pattern moves entirely past c.
- c in the pattern to the left of j: shift is positive, aligning the two copies of c.
- c's rightmost occurrence is to the right of j: j - last[c] is negative (it cannot be zero, because a mismatch at j means c is not the character at j), which would move the pattern backwards, so the
max(1, ...)forces at least one step forward. This is the case the clamp exists for. Example: pattern "ABA" against text "AAABA". At s=0 the comparison goes A=A, then fails at j=1 (pattern B against text A). last['A'] = 2, so j - last = 1 - 2 = -1, which would slide the pattern left; the clamp turns it into a shift of 1 (first line of the "clamp case" trace in the output).
After a full match the code also shifts by 1. The complete algorithm adds a second rule, the good-suffix rule (when the tail of the pattern has matched, shift to the next place where that same tail appears in the pattern), to shift further. Interviews almost always ask only for the bad-character rule; the good-suffix rule, the Galil rule and Horspool's variant are deeper material.
The code
def bad_char_table(pattern, rightmost=True):
"""last[c] = index of the rightmost occurrence of c in the pattern.
rightmost=False keeps the leftmost occurrence instead (wrong; shown only to see why)."""
last = {}
for i, c in enumerate(pattern):
if rightmost or c not in last:
last[c] = i
return last
def bm_search(text, pattern, trace=False, rightmost=True):
"""Boyer-Moore with the bad-character rule only. Returns (matches, comparisons, alignments)."""
n, m = len(text), len(pattern)
last = bad_char_table(pattern, rightmost)
matches, comparisons, alignments, s = [], 0, 0, 0 # s = text index under pattern[0]
while s <= n - m:
alignments += 1 # one placement of the pattern under the text
j = m - 1 # compare right to left
while j >= 0:
comparisons += 1
if pattern[j] != text[s + j]:
break
j -= 1
if j < 0:
matches.append(s)
shift = 1
why = "match"
else:
shift = max(1, j - last.get(text[s + j], -1))
why = f"mismatch text {text[s + j]!r} vs pattern {pattern[j]!r} at j={j}, last[{text[s + j]!r}]={last.get(text[s + j], -1)}"
if trace:
print(f"s={s:2d}: {why} -> shift {shift}")
s += shift
return matches, comparisons, alignments
if __name__ == "__main__":
import random
pattern = "EXAMPLE"
print("table:", bad_char_table(pattern))
text = "HERE IS A SIMPLE EXAMPLE"
print(bm_search(text, pattern, trace=True))
natural = "the quick brown fox jumps over the lazy dog " * 200
found, cmp_, aligns = bm_search(natural, "lazy dog")
print(f"natural text: n={len(natural)}, matches={len(found)}, comparisons={cmp_}, comparisons/n={cmp_ / len(natural):.2f}")
print(f" alignments={aligns}, n/m={len(natural) / 8:.0f}, average shift={len(natural) / aligns:.1f}")
print("clamp case:", bm_search("AAABA", "ABA", trace=True))
print("pattern AAB in AAAB, rightmost table:", bm_search("AAAB", "AAB", trace=True)[0])
print("pattern AAB in AAAB, leftmost table:", bm_search("AAAB", "AAB", trace=True, rightmost=False)[0])
print("empty pattern in abc:", bm_search("abc", ""))
rng = random.Random(4)
dna = "".join(rng.choice("ACGT") for _ in range(10_000))
found, cmp_, _ = bm_search(dna, "ACGTTGCA")
print(f"random DNA: n=10000, m=8, comparisons/n={cmp_ / 10_000:.2f}")
n = 10_000
found, cmp_, _ = bm_search("a" * n, "b" + "a" * 99)
print(f"adversarial: n={n}, m=100, comparisons={cmp_}, comparisons/n={cmp_ / n:.1f}")
found, cmp_, _ = bm_search("a" * n, "a" * 100)
print(f"all a's, pattern a^100: matches={len(found)}, comparisons={cmp_}")
Output
Run in a python:3.12 container (Python 3.12.15), it prints:
table: {'E': 6, 'X': 1, 'A': 2, 'M': 3, 'P': 4, 'L': 5}
s= 0: mismatch text 'S' vs pattern 'E' at j=6, last['S']=-1 -> shift 7
s= 7: mismatch text 'P' vs pattern 'E' at j=6, last['P']=4 -> shift 2
s= 9: mismatch text 'I' vs pattern 'A' at j=2, last['I']=-1 -> shift 3
s=12: mismatch text 'X' vs pattern 'E' at j=6, last['X']=1 -> shift 5
s=17: match -> shift 1
([17], 15, 5)
natural text: n=8800, matches=200, comparisons=3000, comparisons/n=0.34
alignments=1600, n/m=1100, average shift=5.5
s= 0: mismatch text 'A' vs pattern 'B' at j=1, last['A']=2 -> shift 1
s= 1: mismatch text 'B' vs pattern 'A' at j=2, last['B']=1 -> shift 1
s= 2: match -> shift 1
clamp case: ([2], 6, 3)
s= 0: mismatch text 'A' vs pattern 'B' at j=2, last['A']=1 -> shift 1
s= 1: match -> shift 1
pattern AAB in AAAB, rightmost table: [1]
s= 0: mismatch text 'A' vs pattern 'B' at j=2, last['A']=0 -> shift 2
pattern AAB in AAAB, leftmost table: []
empty pattern in abc: ([0, 1, 2, 3], 0, 4)
random DNA: n=10000, m=8, comparisons/n=0.77
adversarial: n=10000, m=100, comparisons=990100, comparisons/n=99.0
all a's, pattern a^100: matches=9901, comparisons=990100
Worked trace: pattern "EXAMPLE" in "HERE IS A SIMPLE EXAMPLE"
The text is 24 characters; the printed search finds the match at index 17 using 15 character comparisons, fewer than the 24 characters of text.
- s = 0: the last characters compared are pattern E against text S (the 7th character of "HERE IS"). S is not in the pattern, so the shift is 6 - (-1) = 7.
- s = 7: E against P. P is at pattern index 4, so the shift is 6 - 4 = 2.
- s = 9: the comparison goes E=E, L=L, P=P, M=M (read right to left), then A against I at j = 2. I is not in the pattern, so the shift is 2 - (-1) = 3.
- s = 12: E against X. X is at pattern index 1, so the shift is 6 - 1 = 5.
- s = 17: all seven characters match, and the match at 17 is recorded.
Why it is sublinear on average for natural-language text
Each alignment costs at least one comparison, and the number of alignments is what the shifts control. A mismatching text character is one of the many letters that do not occur in a short word; for such a character the jump is j + 1, which is the full pattern length when the mismatch is at the pattern's last position (step 1 above) and smaller when the mismatch happens further left (step 3 above). With an alphabet of dozens of symbols and a pattern of length m, most alignments end after one or two comparisons and move forward by a large part of m, so the total is far below n. Count it: the number of alignments is n divided by the average shift, and each alignment costs only a few comparisons. In the run on a repeated English sentence (n = 8800, m = 8) the pattern was placed 1600 times (an average shift of 5.5, against the largest possible 8, n/m = 1100), and those placements cost 3000 comparisons in total, about 1.9 each, which is 0.34 per text character. The effect is weak on tiny alphabets: on random four-letter DNA with a pattern of 8 letters the "random DNA" line of the output shows 0.77 comparisons per text character, more than twice the 0.34 of the English run, because all four letters occur in the pattern, so a mismatch rarely allows a long shift. It also needs a pattern that is not too short.
Complexity
- Preprocessing: O(m) time, O(alphabet size or distinct characters in the pattern) space.
- Search, bad-character rule only: best case about n / m comparisons; typical natural text is sublinear; worst case O(n * m). The printed adversarial run (text of 10,000 a's, pattern b followed by 99 a's) takes 990,100 comparisons, 99 per text character, because each alignment compares 99 characters, then fails on the first character, and the shift is only 1. Searching "a" repeated 100 times in a text of 10,000 a's also takes 990,100 comparisons and reports 9,901 matches, which is the output size times m.
- Full Boyer-Moore adds the good-suffix rule and, with a refinement called the Galil rule (remember which part of the text is already known to match, so it is never compared twice), has an O(n + m) worst case. Horspool's variant keeps only the bad-character idea and looks at the text character under the pattern's last position, which makes the code shorter.
Edge cases and mistakes
- Taking the leftmost occurrence of a character in the table: the shift becomes too large and real matches are skipped. Pattern
AABin textAAABshows it: the first comparison fails at j = 2 on a textA; the rightmost table (last['A'] = 1) shifts by 1 and finds the match at index 1, while the leftmost table (last['A'] = 0) shifts by 2, jumps over it and reports nothing, as printed above. - Forgetting
max(1, ...), which lets a negative shift move the pattern backwards and loop forever (pattern "ABA" in text "AAABA" never finishes without the clamp). - Comparing left to right: the heuristic needs the mismatch at the right end of the alignment to use it fully.
- Using a table of 256 entries on Unicode text without handling code points above that range (a dictionary avoids it).
- An empty pattern needs no special case in this code: the inner loop never runs and every index 0 to n is reported with 0 comparisons (4 matches in
abc, as printed above); a caller who wants no matches for an empty pattern must return early. A pattern longer than the text yields no loop iterations.
Running the code
python bm.py
Save the listing as bm.py. No other files or packages are needed.
Design an autocomplete (typeahead) backend for a global user base: low latency per keystroke, millions of terms, frequent updates, ranking by popularity. Compare the candidate data structures, say how you serve top-k suggestions, and how updates reach the serving copy.
Sample Answer
Recommendation
Serve suggestions from an in-memory trie (a tree keyed by characters, so every prefix is a node) in which every node already stores its top-k completions. A keystroke then costs one walk down the tree of length equal to the prefix plus copying k results, regardless of how many millions of terms exist. Build that structure offline from the query logs, publish it as an immutable versioned snapshot to every region, and swap it in atomically. Put a small "trending" overlay on top for terms that became popular since the last build. Cache hot short prefixes at the edge, and make the client wait briefly after typing stops (debounce) and cancel superseded requests.
Throughout, N is the number of terms in the vocabulary, L is the length of the typed prefix, and k is how many suggestions are returned per keystroke (for example 5 or 10).
Candidate data structures
| Structure | Lookup for a prefix of length L | Top-k by popularity | Memory | Verdict |
|---|---|---|---|---|
| Sorted array of terms plus binary search | O(L log N) to find the range | must scan or heap over every term in the range | smallest | fails on short prefixes |
| Plain trie, no cache | O(L) to reach the node | depth-first walk of the whole subtree | large | same weakness |
| Trie with top-k stored per node | O(L + k) | already there | largest per node | best latency |
Radix (compressed) trie or an FST (finite-state transducer: a compact graph of states and labelled arrows, like a trie that also merges identical endings, e.g. all words ending in -ing, and can carry a value such as a score on its arrows) | O(L) to reach the node; a radix trie then reads top-k stored at its branch points (O(k)), while an FST walks the k best-scoring paths from that node (Lucene's weighted-FST suggester works this way) | stored at branch points (radix trie); derived from arc weights (FST) | much smaller | the production form for large vocabularies |
| Key-value store with one entry per prefix (prefix -> top-k list) | one lookup | stored | large, writes touch every prefix of a term | good when updates must be near-instant |
| General search engine with prefix queries | depends | ranks at query time | flexible | choose when you also need fuzzy matching or typo tolerance |
The sorted-array weakness is concrete. The demo below builds a seeded synthetic vocabulary of 20,000 terms (181,270 characters, 43,158 trie nodes, so prefixes are shared) and answers the same queries both ways. For the prefix c the sorted-array method examines 4,038 terms to pick the best 3; the trie returns the 3 stored entries. For ca it scans 2,012. The answers are identical (asserted in the code).
Demo: top-k per node, and atomic snapshot swap
How the build works, on a tiny case. Each term is walked character by character from the root; at every node on its path (and at the root) the pair (-score, term) is appended. Scores are negated because heapq.nsmallest returns the smallest pairs, and the smallest negated score is the largest score. After all terms are in, each node's list is trimmed to the best K. This is what the first printed block shows: for car (5), cat (9), cab (7) and dog (2), node ca holds cat, cab, car in that order, node car holds only car, and d holds only dog. Building costs one append per character of every term plus one at the root (16 appends for these four terms: 12 characters plus 4 root entries), which is why it is done offline.
The code below demonstrates the top-k-per-node trie, the sorted-array baseline and the snapshot swap. Those three are what a typical interview asks for. The FST, the prefix-keyed store and the search engine are compared in the table above; the FST returns in the memory arithmetic, and the prefix-keyed store and the search engine return in the section on what would change the recommendation.
import random
import heapq
K = 3
class Node:
__slots__ = ("kids", "top")
def __init__(self):
self.kids = {}
self.top = [] # up to K (-score, term) pairs, best first
def build_snapshot(term_scores):
root = Node()
nodes = 1
for term, score in term_scores.items():
node = root
node.top.append((-score, term)) # the root keeps the global list, for the empty prefix
for ch in term:
if ch not in node.kids:
node.kids[ch] = Node()
nodes += 1
node = node.kids[ch]
node.top.append((-score, term))
stack = [root]
while stack:
node = stack.pop()
node.top = heapq.nsmallest(K, node.top)
stack.extend(node.kids.values())
return root, nodes
def suggest(root, prefix):
node = root
for ch in prefix:
node = node.kids.get(ch)
if node is None:
return []
return [t for _, t in node.top]
def suggest_sorted_array(sorted_terms, scores, prefix):
from bisect import bisect_left
lo = bisect_left(sorted_terms, prefix)
scanned, best = 0, []
while lo < len(sorted_terms) and sorted_terms[lo].startswith(prefix):
scanned += 1
best.append((-scores[sorted_terms[lo]], sorted_terms[lo]))
lo += 1
return [t for _, t in heapq.nsmallest(K, best)], scanned
# Tiny hand-checkable build: four terms, K = 3 (the shipped value)
tiny = {"car": 5, "cat": 9, "cab": 7, "dog": 2}
tiny_root, tiny_nodes = build_snapshot(tiny)
print(f"tiny vocabulary {tiny}: {tiny_nodes} nodes")
for prefix in ("", "c", "ca", "car", "d"):
node = tiny_root
for ch in prefix:
node = node.kids[ch]
print(f" node {prefix!r}: top entries (-score, term) = {node.top}")
random.seed(5)
syll = ["ca", "co", "re", "ta", "mi", "no", "ba", "pe", "lu", "si"]
scores = {}
while len(scores) < 20000:
term = "".join(random.choice(syll) for _ in range(random.randint(2, 5)))
scores[term] = random.randint(1, 10**6)
root, nodes = build_snapshot(scores)
total_chars = sum(len(t) for t in scores)
print(f"terms={len(scores)} total characters={total_chars} trie nodes={nodes}")
terms_sorted = sorted(scores)
print("empty prefix:", suggest(root, ""))
for prefix in ("c", "ca", "cabaso", "zz"):
got = suggest(root, prefix)
ref, scanned = suggest_sorted_array(terms_sorted, scores, prefix)
assert got == ref, (prefix, got, ref)
print(f"prefix {prefix!r}: top-{K}={got} | sorted-array scan examined {scanned} terms")
live = {"snapshot": root}
new_scores = dict(scores)
new_scores["cabaso"] = 10**7
new_root, _ = build_snapshot(new_scores)
print("before swap:", suggest(live["snapshot"], "cab")[:1])
live["snapshot"] = new_root
print("after swap:", suggest(live["snapshot"], "cab")[:1])
for terms, avg in ((10_000_000, 20),):
upper = terms * avg
print(f"upper bound nodes for {terms:,} terms x {avg} chars = {upper:,}; top-5 ids x 4 bytes = {upper * 5 * 4 / 1e9:.1f} GB")
Output:
tiny vocabulary {'car': 5, 'cat': 9, 'cab': 7, 'dog': 2}: 9 nodes
node '': top entries (-score, term) = [(-9, 'cat'), (-7, 'cab'), (-5, 'car')]
node 'c': top entries (-score, term) = [(-9, 'cat'), (-7, 'cab'), (-5, 'car')]
node 'ca': top entries (-score, term) = [(-9, 'cat'), (-7, 'cab'), (-5, 'car')]
node 'car': top entries (-score, term) = [(-5, 'car')]
node 'd': top entries (-score, term) = [(-2, 'dog')]
terms=20000 total characters=181270 trie nodes=43158
empty prefix: ['remimipeca', 'nomiluta', 'miperesire']
prefix 'c': top-3=['cocositata', 'cocareba', 'copeba'] | sorted-array scan examined 4038 terms
prefix 'ca': top-3=['camilutaca', 'calunotaca', 'cabamicasi'] | sorted-array scan examined 2012 terms
prefix 'cabaso': top-3=[] | sorted-array scan examined 0 terms
prefix 'zz': top-3=[] | sorted-array scan examined 0 terms
before swap: ['cabamicasi']
after swap: ['cabaso']
upper bound nodes for 10,000,000 terms x 20 chars = 200,000,000; top-5 ids x 4 bytes = 4.0 GB
The two "swap" lines show the update path: a new snapshot is built from updated scores (cabaso is added with a very high score), then the serving pointer is replaced in one assignment, so a request sees either the old snapshot or the new one and never a half-built tree.
Memory arithmetic (assumptions, not measurements)
Assume 10 million terms with 20 characters on average. An uncompressed trie has at most 10,000,000 x 20 = 200,000,000 nodes (real vocabularies share prefixes, so the true count is lower; the ratio of 43,158 nodes for 181,270 characters belongs to this synthetic vocabulary and will differ for real queries). Storing 5 term ids of 4 bytes each on every node is 200,000,000 x 5 x 4 bytes = 4.0 GB for the caches alone, before child pointers. Three ways to keep it affordable: compress single-child chains (radix trie or FST), keep top-k only on nodes above a depth or branching threshold and walk a bounded subtree below it, and shard (split the data across machines) by language or first characters so each machine holds one slice.
Serving path
- The client waits a short pause after the last keystroke, sends the prefix, and cancels the previous request if a new one starts.
- Normalise the prefix the same way the terms were normalised at build time (Unicode normalisation: one canonical byte form for characters that can be written several ways; case folding: mapping
Aandato the same form; and, if the product wants it, accent stripping), soCafe,CAFEandcafécan reach the same node if that is the intent. - A content delivery network or regional cache answers the most common short prefixes without reaching the service (short prefixes are shared by the most users, so caching them has the highest hit rate).
- On a miss the service walks the trie and returns the stored top-k. An empty prefix returns the global top-k (the root node stores it, as the demo's
empty prefixline shows); an unknown prefix returns an empty list. - Personalisation, if required, is a small rerank (re-sorting the k candidates using the user's own signals) of the k candidates, not a separate trie per user.
How updates reach the serving copy
- Log pipeline: search events stream into an aggregator that keeps counts with time decay (each day's count is multiplied by a factor below 1 as it ages, for example halved every week, so recent behaviour outweighs old).
- Builder: on a schedule (for example every few minutes to hourly) a job produces the next snapshot and writes it, versioned, to object storage (a store of named files kept on a remote service, where each snapshot is one downloadable file).
- Distribution: each serving node in each region downloads the new version, loads it beside the current one, runs sanity checks (term count within a range, known queries return known answers), then swaps the pointer. The previous snapshot stays for instant rollback.
- Freshness for breaking terms: a small mutable side index of recently surging terms is merged with the snapshot's top-k at query time, and blocklist entries (takedowns) are applied as a filter at serve time, so removals do not wait for a rebuild.
What would change the recommendation
- Updates that must show up within seconds for the whole vocabulary: use the prefix-keyed store (each term update rewrites its prefixes up to a maximum length) or a mutable trie with per-node bounded heaps, accepting write amplification (one logical update causing many physical writes, here one per prefix of the term) and locking.
- A small vocabulary (tens of thousands of terms): the sorted array is enough and simpler.
- Typo tolerance or mid-word matches: use a search engine with n-gram or edit-distance support, and keep the trie as the fast path for exact prefixes.
Pitfalls
- Ranking by raw all-time counts makes new terms invisible; use decayed counts.
- Rebuilding in place instead of building beside and swapping creates a window of inconsistent reads.
- Storing the strings in every node's cache duplicates memory; store ids or pointers into one string table.
- Forgetting that a term can be deleted (policy, legal): both the snapshot and the overlay need a removal path.
Running the code
python autocomplete_demo.py
Python 3.12, standard library only.
Unlock Full Question Bank
Get access to all 39 String Algorithms and Pattern Matching interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.