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.
Write a Python function find_all_occurrences(pattern: str, text: str) -> List[int] that returns all starting indices where pattern appears in text using the naive O(n*m) algorithm. Explain time and space complexity and show output for pattern='aba' and text='ababa'. Mention edge cases such as empty pattern and pattern longer than text.
Sample Answer
The idea
A substring search asks: at which positions of text does pattern begin? The naive method tries every possible starting position. At each start it lines the pattern up under the text and compares character by character until a character differs (a mismatch) or the whole pattern has matched. Nothing is remembered between starts, which is why it is simple and also why it is slow in the worst case.
Two details decide whether the answer is correct. First, the last position where the pattern can still fit is n - m (n = len(text), m = len(pattern)), so there are n - m + 1 starts to try. Second, matches may overlap: in ababa the pattern aba matches at 0 and at 2, sharing the middle a. So after a match you move on by one position, not by m.
Code
import re
import random
from typing import List
def find_all_occurrences(pattern: str, text: str) -> List[int]:
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1)) # the empty string matches at every gap, including the end
hits = []
for i in range(n - m + 1): # last legal start is n - m, so the range ends at n - m + 1
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
if j == m:
hits.append(i)
return hits
def find_all_off_by_one(pattern: str, text: str) -> List[int]:
n, m = len(text), len(pattern)
hits = []
for i in range(n - m): # BUG: stops one start early
if text[i:i + m] == pattern:
hits.append(i)
return hits
def count_comparisons(pattern: str, text: str) -> int:
n, m = len(text), len(pattern)
count = 0
for i in range(n - m + 1):
j = 0
while j < m:
count += 1
if text[i + j] != pattern[j]:
break
j += 1
return count
def trace(pattern: str, text: str) -> None:
n, m = len(text), len(pattern)
for i in range(n - m + 1):
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
verdict = "MATCH" if j == m else f"mismatch at offset {j}"
print(f" start {i}: {text[i:i + m]!r} vs {pattern!r} -> {verdict}")
print(find_all_occurrences("aba", "ababa")) # overlapping matches
print(find_all_occurrences("", "abc")) # empty pattern
print(find_all_occurrences("abcd", "abc")) # pattern longer than text
print(find_all_occurrences("x", "")) # empty text
print("off-by-one version:", find_all_off_by_one("aba", "ababa"))
print("trace for 'aba' in 'ababa':")
trace("aba", "ababa")
for n in (1000, 2000):
m = 100
worst = count_comparisons("a" * (m - 1) + "b", "a" * n)
best = count_comparisons("b" * m, "a" * n)
print(f"n={n} m={m}: worst-case comparisons={worst} (n-m+1)*m={(n - m + 1) * m}, best-case={best}")
random.seed(7)
for _ in range(500):
t = "".join(random.choice("ab") for _ in range(random.randint(0, 12)))
p = "".join(random.choice("ab") for _ in range(random.randint(0, 5)))
expected = [x.start() for x in re.finditer("(?=" + re.escape(p) + ")", t)]
assert find_all_occurrences(p, t) == expected, (p, t)
print("500 random cases match the regex lookahead reference")
Output:
[0, 2]
[0, 1, 2, 3]
[]
[]
off-by-one version: [0]
trace for 'aba' in 'ababa':
start 0: 'aba' vs 'aba' -> MATCH
start 1: 'bab' vs 'aba' -> mismatch at offset 0
start 2: 'aba' vs 'aba' -> MATCH
n=1000 m=100: worst-case comparisons=90100 (n-m+1)*m=90100, best-case=901
n=2000 m=100: worst-case comparisons=190100 (n-m+1)*m=190100, best-case=1901
500 random cases match the regex lookahead reference
Worked trace for pattern aba in text ababa
n = 5, m = 3, so starts 0, 1 and 2 are tried (the trace lines above come from the trace function). Start 0 matches all three characters. Start 1 compares b with a and fails at offset 0. Start 2 matches again, so the result is [0, 2]. The bug version that loops range(n - m) never tries start 2 and returns [0].
Complexity
- Time: there are
n - m + 1starts and each does at most m comparisons, so the worst case is(n - m + 1) * m, which is O(n*m). It is largest when m is about n/2, giving roughly n^2/4: the product (n - m + 1) * m is a parabola in m with its top near m = n/2, where it is about (n/2) * (n/2). For n = 100 the values are 910, 1,900, 2,550, 1,950 and 990 at m = 10, 25, 50, 75 and 90, against n^2/4 = 2,500 (printed by the small block below). - The worst-case input is one where every attempt matches almost all of the pattern and then fails at the last character: text
aaaa...a, patternaaa...ab. The run above counts 90,100 comparisons for n=1000, m=100, which equals(1000 - 100 + 1) * 100, and 190,100 for n=2000. - The best-case input fails at the first character of every attempt (pattern
bbb...bonaaaa...a): 901 comparisons for n=1000, m=100, which isn - m + 1. - Space: O(1) auxiliary (a few integers), not counting the returned list, which holds one index per match. Comparing with the slice
text[i:i+m] == patternhas the same time bound but allocates a temporary string of length m each time, so it costs O(m) extra space; the index loop avoids that.
Edge cases and common mistakes
- Empty pattern: the code returns every index
0..n(n + 1 positions, including the end), which is what a regex lookahead reports for an empty pattern (a succeeding position at every gap) and what repeatedstr.find("")calls give when advanced one position at a time. Say this choice out loud, because some interviewers expect[]. Either is fine if it is deliberate. - Pattern longer than text:
n - m + 1is zero or negative, the loop body never runs, and the result is[]. In C or C++ with unsigned sizes,n - munderflows to a huge number, so testm > nfirst. - Empty text with a non-empty pattern returns
[]. - Off-by-one loop bound:
range(n - m)instead ofrange(n - m + 1)silently drops a match at the very end (shown above). - Jumping ahead by m after a match drops overlapping matches.
- Writing
text.findin a loop without advancing the start by one loops forever on the same match.
The function was also compared against a regular-expression lookahead reference on 500 random small inputs, including empty strings (the final printed line).
A lookahead (?=...) in a regular expression checks whether the text ahead matches without consuming any characters, so the search position advances by exactly one, and overlapping matches are all reported. That is why the test above uses it as the reference. The small block below shows the contrast with a plain pattern, the empty pattern, and the comparison count:
import re
# A lookahead (?=...) asks "does this match start here?" without consuming characters,
# so the next search position is still the very next index and overlapping matches are found.
print([m.start() for m in re.finditer("aba", "ababa")])
print([m.start() for m in re.finditer("(?=aba)", "ababa")])
print([m.start() for m in re.finditer("(?=)", "abc")], "and str.find on an empty pattern:", "abc".find(""))
# Worst-case comparison count (n - m + 1) * m for n = 100 and several pattern lengths
n = 100
for m in (10, 25, 50, 75, 90):
print(f"n={n} m={m}: (n-m+1)*m = {(n - m + 1) * m}")
print("n*n/4 =", n * n // 4)
Output:
[0]
[0, 2]
[0, 1, 2, 3] and str.find on an empty pattern: 0
n=100 m=10: (n-m+1)*m = 910
n=100 m=25: (n-m+1)*m = 1900
n=100 m=50: (n-m+1)*m = 2550
n=100 m=75: (n-m+1)*m = 1950
n=100 m=90: (n-m+1)*m = 990
n*n/4 = 2500
Running the code
python naive_search.py
python lookahead_demo.py # the small block above
Python 3.12, standard library only.
Implement the KMP string search algorithm in Python: def kmp_search(text: str, pattern: str) -> List[int]. Return all starting indices where the pattern appears in the text in O(n+m) time. Include computation of the prefix-function, handle empty-pattern behavior, and explain complexity.
Sample Answer
The idea
Naive search restarts after every mismatch. KMP keeps a counter j, the number of pattern characters currently matched, and on a mismatch falls back to the next-best partial match using the prefix function pi. pi[i] is the length of the longest proper border of pattern[:i+1] (a border is a prefix that is also a suffix). The text index only moves forward, which is what makes the whole search linear.
For aabaa, the border lengths are: a has none (0), aa has a (1), aab has none (0), aaba has a (1), and aabaa has aa (2). That gives pi = [0, 1, 0, 1, 2]. The next section builds it one cell at a time.
Approach
- Build
pifor the pattern (O(m)). - For each text character
c: whilej > 0andcdiffers frompattern[j], setj = pi[j-1]. Then, ifc == pattern[j], incrementj. - When
j == m, recordi - m + 1, then setj = pi[j-1](not 0) so overlapping matches are still found. - Handle the special cases first: an empty pattern, and a pattern longer than the text.
Building pi by hand
pi is built with the same trick as the search: the pattern is searched against itself. Keep k, the length of the border of the prefix seen so far, and look at the next character p[i]:
- If
p[i] == p[k], the border grows by one:k += 1. - If not, the current border (the first
kcharacters of the pattern, which also end at positioni - 1) cannot be extended byp[i], so try a shorter border. The shorter candidates are exactly the borders of the border. Because the lastkcharacters just read equalp[:k], a border of those characters is also a border ofp[:k], andpi[k-1]is the longest of those. Sok = pi[k-1]jumps straight to the next-longest candidate, and no shorter-but-valid candidate is skipped, since any candidate longer thanpi[k-1]and shorter thankwould contradictpi[k-1]being the longest border ofp[:k]. - If
kreaches 0 andp[i] != p[0], thenpi[i] = 0.
For aabaa the run below shows each step. At i=2, b differs from p[1] = a, so k falls from 1 to pi[0] = 0 and pi[2] = 0. At i=3, a == p[0], so k = 1. At i=4, a == p[1], so k = 2.
The search loop applies the same rule to the text, with j playing the role of k.
Code
import random
from typing import List
def prefix_function(p: str) -> List[int]:
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def prefix_function_traced(p: str) -> List[int]:
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
print(f" i={i} {p[i]!r} != p[{k}]={p[k]!r}: k {k} -> {pi[k - 1]}")
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
print(f" i={i} {p[i]!r}: pi[{i}]={k} (prefix {p[:k]!r} = suffix {p[i - k + 1:i + 1]!r})")
return pi
def kmp_search(text: str, pattern: str) -> List[int]:
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
pi = prefix_function(pattern)
hits, j = [], 0 # j = how many pattern chars currently match
for i, c in enumerate(text):
while j > 0 and c != pattern[j]:
j = pi[j - 1]
if c == pattern[j]:
j += 1
if j == m:
hits.append(i - m + 1)
j = pi[j - 1] # keep the longest border so overlapping matches are found
return hits
def kmp_search_traced(text: str, pattern: str) -> List[int]:
pi = prefix_function(pattern)
hits, j = [], 0
for i, c in enumerate(text):
while j > 0 and c != pattern[j]:
print(f" i={i} {c!r} != pattern[{j}]={pattern[j]!r}: j {j} -> {pi[j - 1]}")
j = pi[j - 1]
if c == pattern[j]:
j += 1
line = f" i={i} {c!r}: j={j}"
if j == len(pattern):
hits.append(i - len(pattern) + 1)
j = pi[j - 1]
line += f" -> MATCH at {hits[-1]}, j reset to {j}"
print(line)
return hits
def text_comparisons(text: str, pattern: str) -> int:
pi = prefix_function(pattern)
j = count = 0
for c in text:
while j > 0 and c != pattern[j]:
count += 1
j = pi[j - 1]
count += 1
if c == pattern[j]:
j += 1
if j == len(pattern):
j = pi[j - 1]
return count
print("building pi('aabaa'), pi[0] = 0:")
print("pi('aabaa') =", prefix_function_traced("aabaa"))
print("trace of 'aabaa' in 'aabaabaaa':")
print(kmp_search_traced("aabaabaaa", "aabaa"))
print(kmp_search("ababa", "aba"), kmp_search("abc", ""), kmp_search("abc", "abcd"))
for n in (1000, 2000, 4000):
c = text_comparisons("a" * n, "a" * 99 + "b")
print(f"n={n}: character comparisons={c}, 2n={2 * n}")
random.seed(11)
for _ in range(2000):
t = "".join(random.choice("ab") for _ in range(random.randint(0, 14)))
p = "".join(random.choice("ab") for _ in range(random.randint(0, 6)))
expected = [i for i in range(len(t) - len(p) + 1) if t.startswith(p, i)]
assert kmp_search(t, p) == expected, (t, p)
print("2000 random cases match str.startswith scan")
Output:
building pi('aabaa'), pi[0] = 0:
i=1 'a': pi[1]=1 (prefix 'a' = suffix 'a')
i=2 'b' != p[1]='a': k 1 -> 0
i=2 'b': pi[2]=0 (prefix '' = suffix '')
i=3 'a': pi[3]=1 (prefix 'a' = suffix 'a')
i=4 'a': pi[4]=2 (prefix 'aa' = suffix 'aa')
pi('aabaa') = [0, 1, 0, 1, 2]
trace of 'aabaa' in 'aabaabaaa':
i=0 'a': j=1
i=1 'a': j=2
i=2 'b': j=3
i=3 'a': j=4
i=4 'a': j=5 -> MATCH at 0, j reset to 2
i=5 'b': j=3
i=6 'a': j=4
i=7 'a': j=5 -> MATCH at 3, j reset to 2
i=8 'a' != pattern[2]='b': j 2 -> 1
i=8 'a': j=2
[0, 3]
[0, 2] [0, 1, 2, 3] []
n=1000: character comparisons=1901, 2n=2000
n=2000: character comparisons=3901, 2n=4000
n=4000: character comparisons=7901, 2n=8000
2000 random cases match str.startswith scan
Worked trace: aabaa in aabaabaaa
The printed table shows pi('aabaa') = [0, 1, 0, 1, 2]. The first five characters match and give a hit at 0. The code then sets j = pi[4] = 2, because the last two matched characters aa are also the pattern's first two, and continues with b, a, a, producing the overlapping hit at 3 without looking back at the text. At the last character, a differs from pattern[2] = b, so j falls from 2 to pi[1] = 1, then a matches pattern[1], leaving j = 2. Result: [0, 3].
Why the search is O(n + m)
j goes up by at most 1 per text character, so over the whole run it rises at most n times. Every fallback lowers it, so there can be at most n fallbacks in total, even though one character may trigger several. The loop therefore does at most n comparisons that advance plus n that fall back. The measurement above, taken on text aaaa...a with pattern aaa...ab (99 a's then b), shows character comparisons of 1,901, 3,901 and 7,901 for n = 1,000, 2,000 and 4,000, always under 2n. Building pi is O(m) by the same argument. Space is O(m) for pi, plus the output list.
Edge cases
- Empty pattern: returns
[0, 1, ..., n](every gap), consistent withstr.find(""). State the convention. - Pattern longer than text: returns
[]immediately (also avoids a uselesspibuild). - Overlapping matches:
ababa/abagives[0, 2]. If the code resetj = 0after a match, the second hit would be lost. Onaabaabaaawith patternaabaathat variant reports only[0]and misses the match at 3. - Pattern equal to text, single-character pattern and repeated characters (
aaaa) all work, since the same loop handles them. - Unicode: indexing is by Python code point, so results are code point offsets, not byte offsets.
Common mistakes
ifinstead ofwhilein the fallback loop.- Reading
pattern[j]whenj == m(IndexError); resettingjright after a match prevents it. - Using
pi[j]instead ofpi[j-1]. - Building
pifor the single stringpattern + '#' + text, a well-known alternative way to search. Every value ofpithat equalslen(pattern)marks a match ending there, and the#separator stops any border from running past the pattern, so it must not appear in either string. The shipped code uses the two-pass search instead, which needs no separator.
The function was checked against a str.startswith scan on 2,000 random binary strings (final printed line).
Running the code
python kmp_search.py
Python 3.12, standard library only.
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.
Implement a rolling-hash based substring search (Rabin-Karp) in Java that finds all occurrences of a fixed-length pattern in a text. Use base=256 and mod=1000000007. Show how to update the rolling hash in O(1) when sliding the window and describe how to handle and detect hash collisions.
Sample Answer
The idea
Rabin-Karp compares numbers instead of strings. Read each length-m window of the text as a number in base 256 (one "digit" per character), reduce it modulo a prime (take the remainder after dividing by a prime number MOD, so the value stays small) so it fits in a long, and compare it with the pattern's number. A window whose number differs cannot be a match. When the numbers agree the code compares the actual characters, because two different strings can produce the same number (a hash collision). The rolling update turns the hash of window i into the hash of window i+1 in O(1): remove the leading character's contribution, shift everything one place (multiply by the base), and add the new character.
The update formula
With high = BASE^(m-1) mod MOD (the weight of the leading character):
window = ((window - text[i] * high) mod MOD * BASE + text[i+m]) mod MOD
Two Java details matter. The product text[i] * high is at most 65,535 * (10^9 + 6), about 6.6 * 10^13, and window * BASE is under 10^9 * 256; both fit in a 64-bit long (max about 9.2 * 10^18), so no overflow occurs. And Java's % takes the sign of its left operand, so window - drop can be negative; the code adds mod before the remainder (+ mod) to keep the hash in [0, MOD).
The slide with real numbers
Here m = 3, so high = 256^2 = 65,536. Start from window zab, whose hash is 8,020,322 (printed below).
- Drop
z(code 122):122 * 65,536 = 7,995,392, and8,020,322 - 7,995,392 = 24,930. What is left is the hash ofabas a two-digit number. - Shift left by one place:
24,930 * 256 = 6,382,080. - Add the new character
c(code 99):6,382,080 + 99 = 6,382,179, which is the hash ofabc.
The next slide drops a (97) and adds p (112): 97 * 65,536 = 6,356,992, then 6,382,179 - 6,356,992 = 25,187, then 25,187 * 256 + 112 = 6,447,984, the printed hash of bcp. Every value here is below the modulus, so no remainder changes anything; the remainder only matters once a window is long enough to exceed 1,000,000,007.
Code
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RabinKarp {
static final long BASE = 256;
static final long MOD = 1_000_000_007L;
// Returns every start index of pattern in text. falsePositives[0] counts hash hits that failed verification.
static List<Integer> search(String text, String pattern, long mod, int[] falsePositives, boolean verbose) {
int n = text.length(), m = pattern.length();
List<Integer> hits = new ArrayList<>();
if (m == 0) {
for (int i = 0; i <= n; i++) hits.add(i);
return hits;
}
if (m > n) return hits;
long high = 1; // BASE^(m-1) mod mod, the weight of the leading char
for (int i = 1; i < m; i++) high = high * BASE % mod;
long target = 0, window = 0;
for (int i = 0; i < m; i++) {
target = (target * BASE + pattern.charAt(i)) % mod;
window = (window * BASE + text.charAt(i)) % mod;
}
for (int i = 0; i + m <= n; i++) {
if (verbose) System.out.println(" window " + i + " " + text.substring(i, i + m) + " hash=" + window + " target=" + target);
if (window == target) {
if (text.startsWith(pattern, i)) hits.add(i); // verify: equal hashes do not imply equal strings
else falsePositives[0]++;
}
if (i + m < n) {
long drop = text.charAt(i) * high % mod;
window = ((window - drop + mod) % mod * BASE + text.charAt(i + m)) % mod; // + mod keeps it non-negative
}
}
return hits;
}
// Same loop without the "+ mod" fix: Java's % keeps the sign of the dividend.
static List<Integer> searchNegativeBug(String text, String pattern, long mod) {
int n = text.length(), m = pattern.length();
List<Integer> hits = new ArrayList<>();
long high = 1;
for (int i = 1; i < m; i++) high = high * BASE % mod;
long target = 0, window = 0;
for (int i = 0; i < m; i++) {
target = (target * BASE + pattern.charAt(i)) % mod;
window = (window * BASE + text.charAt(i)) % mod;
}
for (int i = 0; i + m <= n; i++) {
if (window == target && text.startsWith(pattern, i)) hits.add(i);
if (i + m < n) window = ((window - text.charAt(i) * high % mod) * BASE + text.charAt(i + m)) % mod;
}
return hits;
}
static List<Integer> naive(String text, String pattern) {
List<Integer> hits = new ArrayList<>();
for (int i = 0; i + pattern.length() <= text.length(); i++)
if (text.startsWith(pattern, i)) hits.add(i);
return hits;
}
public static void main(String[] args) {
int[] fp = new int[1];
System.out.println("zabcp / abc, mod 1e9+7:");
System.out.println(search("zabcp", "abc", MOD, fp, true));
System.out.println("ababa / aba: " + search("ababa", "aba", MOD, fp, false));
System.out.println("empty pattern in 'abc': " + search("abc", "", MOD, fp, false));
System.out.println("pattern longer than text: " + search("ab", "abc", MOD, fp, false));
System.out.println("negative-modulo bug, mod 101: " + searchNegativeBug("zabcpqrabc", "abc", 101)
+ " vs correct " + search("zabcpqrabc", "abc", 101, fp, false));
Random rnd = new Random(42);
String alphabet = "abé日本";
int falseAlarms = 0;
for (int t = 0; t < 3000; t++) {
StringBuilder s = new StringBuilder(), p = new StringBuilder();
int n = rnd.nextInt(40), m = rnd.nextInt(5);
for (int i = 0; i < n; i++) s.append(alphabet.charAt(rnd.nextInt(alphabet.length())));
for (int i = 0; i < m; i++) p.append(alphabet.charAt(rnd.nextInt(alphabet.length())));
long mod = (t % 2 == 0) ? MOD : 101;
int[] f = new int[1];
List<Integer> got = search(s.toString(), p.toString(), mod, f, false);
if (!got.equals(naive(s.toString(), p.toString()))) throw new AssertionError(s + " / " + p);
if (mod == 101) falseAlarms += f[0];
}
System.out.println("3000 random cases (half with mod 101, wide chars) match the naive scan; hash hits rejected by verification (mod 101 runs): " + falseAlarms);
}
}
Output (Java 21, Temurin, in a container):
zabcp / abc, mod 1e9+7:
window 0 zab hash=8020322 target=6382179
window 1 abc hash=6382179 target=6382179
window 2 bcp hash=6447984 target=6382179
[1]
ababa / aba: [0, 2]
empty pattern in 'abc': [0, 1, 2, 3]
pattern longer than text: []
negative-modulo bug, mod 101: [] vs correct [1, 7]
3000 random cases (half with mod 101, wide chars) match the naive scan; hash hits rejected by verification (mod 101 runs): 150
Reading the output
- For
abcinzabcpthe pattern hash is 6,382,179. Becauseabcas a base-256 number (97*256^2 + 98*256 + 99) is below the modulus 1,000,000,007, the hash equals the exact number. Window 0 (zab) gives 8,020,322, window 1 (abc) matches, window 2 (bcp) gives 6,447,984, so only window 1 is verified, giving[1]. - Overlapping matches:
abainababagives[0, 2]. - Negative-modulo pitfall: with modulus 101, searching
abcinzabcpqrabcgives[]without the+ modfix, because the negative window hash can never equal the non-negative pattern hash (a silent wrong answer, no exception), and[1, 7]with it. - The random test compares the result with a plain
startsWithscan on 3,000 seeded random inputs over the alphabeta,b,é,日,本; half run with modulus 101 so collisions actually happen (150 hash hits were rejected by the verification step), and every result still matches.
Choosing base and modulus
- The modulus should be a prime well above the number of windows: a text with W windows and a modulus near W makes collisions between unrelated windows likely, since each window has about a 1 in MOD chance of matching the pattern's hash by accident, so the expected number of wasted verifications is about W / MOD. With 10^9 + 7 and a text of a million windows that is about one in a thousand. 10^9 + 7 also keeps all intermediate products inside a
long; a much larger modulus needs wider multiplication (for example 128-bit arithmetic, a multiply whose result is twice as many bits wide as along). - The base is normally at least the alphabet size. Java
charvalues go up to 65,535, larger than 256. Correctness is unaffected because every hash hit is verified; the hash is still a polynomial modulo a prime, and only the collision rate is a concern. - A fixed, known pair (256, 10^9 + 7) can be attacked with crafted strings that all collide, which turns every window into a verification and the search into O(n*m). In a service that searches untrusted text, choose the base at random at startup (any value from 2 to MOD - 2); for a random base the collision chance for two distinct strings of length m is at most (m - 1) / (MOD - 3), which is about (m - 1) / MOD. The reason: two strings collide when the polynomial formed by their character differences, which is not zero and has degree below m, evaluates to 0 mod MOD at the base. A nonzero polynomial of degree d has at most d roots modulo a prime (for example
x^2 - 5x + 6is 0 only at x = 2 and x = 3), so at most m - 1 of the MOD - 3 allowed bases cause a collision. An attacker who cannot see the random base cannot craft such strings. This kind of crafted-collision attack on a hash table or search is often called hash flooding. - Wide alphabets: Java strings are UTF-16, so
charAtreturns code units, and a character outside the Basic Multilingual Plane (the first 65,536 Unicode code points, the ones that fit one UTF-16 code unit, a 16-bit value) such as an emoji is two units. This code therefore matches by code unit; hashcodePoints()instead if you need code point semantics.
Handling and detecting collisions
Detection is the startsWith check on every hash hit; falsePositives counts the rejected ones. A hash hit that fails verification is a collision, never a result. Without verification a collision gives a wrong match.
Complexity
- Expected time O(n + m): O(m) to hash the pattern and the first window, O(1) per slide, and O(m) verification only on a hash hit (true matches, plus rare collisions).
- Worst case O(n*m) when many windows hit (all windows equal the pattern, as in
aaaa.../aaa, or an adversarial text). - Space O(1) beyond the result list;
startsWithdoes not allocate. (Thesubstringcall in the verbose trace is the only allocation and exists just for printing.)
Edge cases
Empty pattern returns all indices 0..n; a pattern longer than the text returns an empty list; a pattern equal to the text works (one window); text and pattern that contain characters above 255 work because hashes are verified.
Running the code
javac RabinKarp.java && java RabinKarp
Used with JDK 21; no other config.
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
That is every published String Algorithms and Pattern Matching question for Full-Stack Developer so far. Browse the other topics in this category, or practice this one interactively.