Tries, automata and pattern matching
Single- and multipattern text matching underpin antivirus software, intrusion detection and code scanning. Study tries and radix trees, KMP's prefix function, Rabin-Karp rolling hashes, and Aho-Corasick matching of thousands of patterns in linear time. Compare backtracking regex engines with automaton simulation and examine their connection to ReDoS.
After this lesson you can
- Implement a trie and a radix tree and analyze their space.
- Calculate the prefix function and demonstrate that KMP is linear with an amortized argument.
- Implement Rabin-Karp with a random base and bound the false-positive probability.
- Build the Aho-Corasick automaton and use it to scan signatures over a corpus of code.
- Explain why some regular expression engines are vulnerable to ReDoS and how RE2 and Rust regex avoid it.
Before you start
Motivation: large texts, many patterns
A code scanner receives a repository several gigabytes in size and a list of signatures: dangerous function names such as eval, os.system and pickle.loads; credential prefixes such as AKIA, ghp_ and xoxb-; and private-key headers. It must report every position where each occurs. Antivirus and intrusion-detection systems do the same with thousands of signatures on a network stream that cannot wait. Code search, editor autocomplete, routers selecting a packet’s next hop, and inference servers reusing memory for an already processed prompt all solve variants of one problem: match many strings against a text without rereading the text separately for every string.
- Autocomplete and dictionaries. Given the prefix you have typed, list the keys extending it in time depending on the prefix, rather than the dictionary’s total number of words.
- IP routing. A routing table contains bit prefixes; a packet follows the route with the longest prefix matching its address. Linux’s IPv4 routing table, for example, uses a level-compressed trie.
- Language-model prefix caching. Requests sharing a prompt prefix share the attention computations for that prefix. Systems such as SGLang organize these memories in a radix tree indexed by token sequences, evicting the least-used leaves.
- Tokenization. Longest-match tokenizers such as WordPiece seek the longest vocabulary token beginning at each position. A vocabulary trie finds it in a single descent. BPE, discussed in m20, works differently: it applies merges in priority order and need not return the longest token.
- Security scanners. A signature-matching engine must run in time linear in input size even when an attacker controls the input. This rules out methods whose worst-case behavior depends on the input’s contents.
The lesson follows three threads. First, strings as prefix trees: tries and radix trees. Second, single-pattern matching in linear time: KMP’s prefix function, with an amortized argument as in the lesson on amortized analysis, and Rabin-Karp’s rolling hash, building on universal hashing. Third, multiple and structured patterns: Aho-Corasick automata and regular-expression engines, where m01’s automata theory determines whether an expression is a tool or a weapon against your own server.
Tries: keys as paths
A string dictionary based on hash tables tells you whether a string is present but knows nothing about prefixes: listing keys beginning with rub would require scanning every key. A balanced search tree orders them, but each comparison can cost as much as the string’s length. A trie instead uses the letters themselves as edges.
A node exists if and only if its string is a prefix of some key: the trie is the union of the keys’ paths, sharing their beginnings. The operations follow directly from this definition and are all guided by the input string.
insertar(w): descend along the letters of , creating missing nodes, and mark the last node terminal.buscar(w): descend along the string and return true if you reach a terminal node.con_prefijo(q): descend along , then traverse the subtree rooted there; it contains exactly the keys beginning with .
Proof
Each key contributes at most new nodes, one per character, to those already present; only the root is not contributed by a character. Summing gives . Each operation consumes one character per traversed edge. In the subtree, every node has an incoming edge and every internal node leads to a key, so traversal visits at most nodes.
∎The bound is attained only when keys share no prefixes. Repeated beginnings, such as function names from one library, file paths or IP addresses, reduce the node count. In the first interactive example, seven Latin-script keys total characters and their trie has nodes.
How children are stored
The engineering question is how to represent a node’s children. Four common choices have costs differing by a factor depending on .
| Representation | Node space | Son by symbol | Notes |
|---|---|---|---|
| Array of pointers | With and 8-byte pointers, 2 KiB per node even if it has a child | ||
Hash table (dict) | expected | The usual in Python; with overloading by input | |
| List of symbol and pointer pairs | Compact; good if the nodes have few children | ||
| Symbol search tree | Free alphabetical order: Bentley and Sedgewick’s ternary trie |
The array representation causes the most common memory mistake. By the proposition, keys of length 12 have at most nodes; random byte strings have more than a million, because almost nothing is shared after the third character. An array of 256 pointers per node takes roughly to GB. A dict per node takes hundreds of megabytes: even an empty Python dictionary occupies tens of bytes and grows in jumps. Edge lists take much less. Node count determines actual space usage, and a trie suffers here: almost every node of a real trie has just one child.
Radix trees: compressing the paths
This suggests compression: a chain of nonterminal nodes with one child adds no branching decisions, only length. Replace it with one edge labeled by the entire substring.
Proof
Partition the nonroot nodes into leaves, internal nodes with one child, and internal nodes with at least two children. Leaves and single-child internal nodes are terminal: radix-tree compression requires the latter to be terminal, and a nonterminal leaf would not be a prefix of any key. Each key marks one node, so . To bound , count edges. Their number is the number of nodes minus one, , and also the sum of all child counts, which is at least : branching nodes contribute at least two, single-child nodes contribute one, and the root contributes at least one since . From we obtain . Total node count is therefore . Each label stored as a key-start-length triple takes three words, and there are fewer than edges.
∎The bound is tight: the seven Latin-script keys in the interactive example give exactly nodes. Compression makes buscar compare substrings on each edge rather than one character, but each query character is still read only once, so cost remains . Visited-node count falls from to at most one plus the path’s branching or terminal nodes. Insertion may need to split an edge, introducing a node where the key diverges from its label.
Radix trees occur in three practical settings. In routing tables, a binary trie over address bits implements longest-prefix matching and skips bits where no branching occurs, as in Morrison’s Patricia tree (1968); kernels additionally compress levels. In an inference server’s prefix cache, keys are token sequences and nodes point to attention-memory blocks; when memory runs out, the least-recently used leaf is evicted. In longest-match tokenization, such as WordPiece and its variants, a vocabulary trie finds the longest available token at each position in one descent.
A pattern in a text: brute force and why it backtracks
Now return to the classical problem: given text and pattern , find every position satisfying . The direct method aligns the pattern at every and compares until the first mismatch. It is correct but costs in the worst case: with and , each alignment compares characters before failing on the last, for comparisons in total. With and , that is comparisons merely to report no matches.
The waste lies in what the method discards. When comparison fails at pattern position , the preceding text characters are already known to equal . Brute force forgets this, resets the text pointer to and rereads them. KMP reuses what was already read.
Borders and the prefix function
For , suppose the text matches and then fails at . The matched string is ; the next possible alignment starts where a suffix of that string matches a prefix of the pattern. Suffix is also a pattern prefix, so comparison can continue at position without rereading text.
For , : after matching , so , the longest border has length . A fact about borders lets us traverse all of them.
Proof
If is a border of , it is a suffix of , itself a suffix of , so is a suffix of . It is also a prefix of , itself a prefix of , so it is a prefix of . Hence is a border of . Conversely, let be a border of with . Both and the border of length are suffixes of , and , so is a suffix of . Both are prefixes of , so is a prefix of . Thus is a border of .
∎The algorithm and interactive visualization
With state equal to the number of pattern characters matched against the end of the text read so far, KMP needs one state variable: if , advance and ; otherwise, if , replace by without moving ; if , advance . When reaches , record a match and continue with . The whole pattern has borders too, allowing overlapping matches.
Correctness follows from one question: after a mismatch with matched characters, which alignments can we discard without inspecting them?
Proof
If were a match with , the text would equal both under alignment and under alignment . Consequently would be a border of of length , contradicting the maximality of . For , the border of length equals by definition, so that alignment is consistent with the characters already read. If , there is no border and the algorithm jumps to alignment .
∎If the new also mismatches, repeat the argument with . The border lemma guarantees that this visits every border in decreasing length order, skipping none.
Computing the prefix function is KMP on the pattern itself
Compute using the same loop with and pattern : is the value of reached after reading . This is the interactive’s ‘Compute π’ mode, and explains why preprocessing and searching share the same analysis.
Proof
Apply the potential method with , initially . Each comparison does one of three things. On a match, and both increase by one: actual cost and . A mismatch with increases and leaves unchanged. A mismatch with replaces by , so . At most comparisons increase , because the text is read once. Comparisons decreasing cannot outnumber the increases of , and there are at most of those: increases only when advances and never becomes negative. Total comparisons: .
∎This is the same trick as counting bit changes in a binary counter: a comparison that falls back pays using potential accumulated by advancing comparisons. The equivalent proof for is the lesson’s first exercise. The text pointer never moves backward, so KMP also works on a stream that cannot be stored, such as a network connection or another process’s output. It keeps only state .
Rabin-Karp: compare fingerprints
KMP avoids comparing characters already seen. Rabin and Karp (1987) propose a different approach: compare fingerprints of text windows with the pattern’s fingerprint, inspecting characters only when the fingerprints agree. Updating the fingerprint when the window slides by one character must take .
With verification, the algorithm is always correct: equal hashes for distinct strings, false positives, merely cost time. The question determining whether the method is linear is therefore how many false positives occur.
Proof
Let , a polynomial over the field . A collision occurs exactly when . Since and symbols are smaller than , some coefficient is nonzero, so is not the zero polynomial. Its degree is at most , giving at most roots in . Of the possible values of , at most are roots. The second claim follows by linearity of expectation, summing over the windows distinct from the pattern.
∎Two observations. First, the base is random, rather than the text: the bound applies to any fixed pair of strings, as in universal hashing. The family is almost universal with . Second, with the Mersenne prime , whose modular reduction takes only a few operations, and and , expected false positives are fewer than . Verifying each genuine match costs , giving expected total time .
Rabin-Karp does not beat KMP for one pattern, but handles something KMP cannot easily do: many equal-length patterns. Store the hashes of the patterns in a hash table and query each window’s hash. Expected time is plus per candidate match requiring verification, so affects only preprocessing. Expected false positives rise to at most , negligible with . Rolling fingerprints, not always using this polynomial, also underpin plagiarism detection, rsync’s search for known blocks, and content-defined chunking in backup tools, which splits a stream wherever the rolling hash satisfies a condition.
Aho-Corasick: all patterns in one pass
Searching for patterns with KMP passes costs , where . Aho and Corasick (1975), working on bibliographic search, showed how to do it in , with reported occurrences. Their idea generalizes KMP using the patterns’ trie as its skeleton.
After reading , the automaton’s state is the trie node whose string is the longest suffix of the text read so far that is a prefix of some pattern. If that node has no edge for the next character, fall back to the next-longest suffix that remains a pattern prefix. A failure link implements this generalization of .
Proof
Induct on . Suppose the state before reading was , the longest suffix of that is a prefix. Suffixes of that are pattern prefixes have the form , where is a suffix of that is a prefix and is also a prefix. The candidates for are and those suffixes of represented by trie nodes: the chain , by the border lemma’s argument applied to trie nodes. The loop visits this chain in decreasing length order and stops at the first node with a child, giving the longest suffix. If none has one, only the empty suffix remains, represented by the root. For outputs, a pattern ends at exactly when it is a suffix of . Every pattern suffix of is itself a prefix, so its node lies along . Output links skip precisely to the terminal nodes.
∎Breadth-first construction of failure links
Build failure links level by level using breadth-first search. Root children fail to the root. For a node reached from by symbol , with already processed, start at and follow failure links until reaching a node with a child. That child is , or use the root if none exists. This is exactly the loop. Output links follow from : use if is pattern-terminal, otherwise .
Proof
Scanning. Let be state depth after reading . Reading a character increases depth by at most one; each failure jump decreases it by at least one. Since , jumps cannot outnumber the at most increases. Each step along an output-link chain emits an occurrence, giving total output work. Construction. Let be a pattern and the nodes along its path. Searching for the failure of starts at . The lemma gives , while each failure-chain step decreases depth by at least one. The same amortized argument as KMP gives per pattern and in total.
∎Without output links, scanning remains correct but loses the guarantee: determining whether the current state ends another pattern would require walking its entire failure chain at every character, with cost proportional to chain length rather than reported matches.
A variant removes jumps by computing the complete transition function: the child of when present, otherwise , with missing root transitions returning to the root. The same BFS builds a deterministic finite automaton with states, consuming each character in exactly one transition. It is the DFA from m01 recognizing ‘the text ends with one of the patterns’. Compare this with the subset construction: the NFA for , a trie with a root loop, has at most states, and subset construction could produce , but only are reachable here because the longest suffix determines each reachable subset, as the invariant lemma shows. The complete table’s cost is memory, , which real engines compress.
Regular expressions: two families of engines
So far, patterns have been fixed strings. A regular expression describes a language, as in (a|b)*abb, [0-9]+\.[0-9]+ or ^[a-z]+@[a-z]+\.com$. There are two ways to build a matcher, and their difference is this section’s subject.
Automaton simulation. Thompson’s construction (1968) turns expression into an NFA with states: one per literal, plus branching states for |, *, + and ?. To test membership of a length- string, maintain the set of active states and advance one character at a time. There are never more than active states, giving time and memory for every expression and every input. Cache visited sets as DFA states, constructing only those needed, a lazy DFA, and each character costs once its state has been constructed.
Backtracking. Engines used by Perl, PCRE, Java, JavaScript, Python’s re and Ruby recursively traverse an expression. At each branch, they try one alternative, backtrack if it fails, and try the next. They support nonregular extensions such as backreferences, \1, and are fast on typical inputs. But failures require undoing work, and branches accumulate. Since version 3.2, Ruby memoizes failed state-position pairs, making backtracking linear for most expressions, though not all, including expressions with backreferences.
An example that costs
Consider (a+)+b on , without a final . Each can continue the current block or start a new block. The engine does not discover that there is no until the end, so it must try every partition of into blocks.
Proof
Every partition of into consecutive nonempty blocks is a recognition path through (a+)+ consuming the entire string. The engine must exhaust them before concluding that no follows. Partitions correspond to subsets of the boundaries between characters, giving . For the NFA, the active-state set after every character is the same constant-sized set, containing the loop states and the state, updated in constant time per character.
The next explorer draws this attempt tree and, below it, the NFA’s active states for the same input. This teaching engine counts visits to state-position pairs and requires the expression to match the entire input. It is not any language’s actual engine, but demonstrates the phenomenon.
(a|aa)+b (Fibonacci growth), a*a*a*b (polynomial, n³) and a+b, which accepts the same language as (a+)+b and is linear. Add the suffix «b» and you will see that the input is accepted and the backtracking succeeds at the first attempt: the danger is in the failures.ReDoS: an algorithmic complexity attack
ReDoS, regular expression denial of service, is the algorithmic complexity attack exploiting this behavior: evaluating a vulnerable expression on attacker-controlled input can occupy a thread, sometimes an entire server, for minutes. It is the same pattern as hash flooding from m08, replacing collisions with ambiguity. These are real incidents. According to Stack Overflow’s postmortem, in July 2016 a whitespace-trimming expression applied to a post with about twenty thousand consecutive spaces took the site down. Cloudflare’s July 2019 postmortem describes a new web-application firewall rule whose excessive regex backtracking pushed server CPU utilization to 100% and interrupted service for almost half an hour. Both expressions were legitimate; their behavior on hostile inputs had not been examined.
What makes an expression vulnerable? Its NFA’s ambiguity: some strings have many recognition paths. Exponential behavior occurs when a state has two distinct cycles consuming the same word, as with the two ways to distribute across (a+)+, or the alternatives a and aa in (a|aa)+. Polynomial behavior arises from sequential loops consuming the same word, as in a*a*a*, with three loops over . If the NFA is unambiguous, recognizing every string along one path, backtracking does not explode for this reason.
Defenses. None replaces the others.
- Use a linear-time engine for untrusted input: RE2, Rust’s
regexcrate, Go’sregexppackage, .NET’sNonBacktrackingoption and Hyperscan simulate NFAs or build DFAs on demand, guaranteeing . In exchange, they omit backreferences and some assertions. - Rewrite without ambiguity:
(a+)+bis equivalent toa+b, and^(\d+)*$to^\d*$. Possessive quantifiers and atomic groups,(?>...), available in Python since 3.11 and in Java and PCRE, prevent backtracking over already consumed input. - Limit input: impose a maximum length before applying the expression, then evaluate it under a time budget in an isolated process that can be terminated.
- Analyze expressions in the repository with static ambiguity detectors such as
recheckorregexploit. Test your own expressions with increasingly long inputs and measure cost growth.
In the tools
| Tool | Strategy | Time guarantee |
|---|---|---|
grep of GNU | Lazy DFA with prefix filtering of fixed strings; backtracking only if there are references backward | linear without references backward |
RE2 (Google) and the package regexp of Go | NFA and lazy DFA | linear en |
Crate regex of Rust (and ripgrep) | Lazy DFA, NFA, and literals with Aho-Corasick and SIMD | |
| Hyperscan (and its derivative Vectorscan) | NFA and DFA with vectorization, many expressions at once and flow mode | linear, designed for thousands of rules |
Module re from Python, PCRE, Java, JavaScript | back | exponential in the worst case |
Laboratory: a signature scanner from scratch
We will implement everything from scratch and check it against the definitions. The first cell implements a trie, counts radix-tree nodes, computes the prefix function for KMP, and implements Rabin-Karp with a random base. Each part is verified against brute force.
import random, time
# ---------- trie con diccionarios ----------
class Nodo:
__slots__ = ("hijos", "fin")
def __init__(self):
self.hijos = {}
self.fin = False
def insertar(raiz, palabra):
nodo = raiz
for c in palabra:
nodo = nodo.hijos.setdefault(c, Nodo())
nodo.fin = True
def descender(raiz, prefijo):
"""Nodo al que llega el prefijo, o None. Cuesta O(|prefijo|), con independencia de cuántas claves haya."""
nodo = raiz
for c in prefijo:
nodo = nodo.hijos.get(c)
if nodo is None:
return None
return nodo
def con_prefijo(raiz, prefijo):
"""Todas las claves con ese prefijo: O(|prefijo| + tamaño del subárbol)."""
nodo = descender(raiz, prefijo)
salida, pila = [], ([(nodo, prefijo)] if nodo else [])
while pila:
v, s = pila.pop()
if v.fin:
salida.append(s)
for c, h in v.hijos.items():
pila.append((h, s + c))
return sorted(salida)
def contar(raiz):
"""(nodos del trie, nodos del árbol radix): el radix conserva la raíz, los finales de clave y los nodos con != 1 hijo."""
trie = radix = 0
pila = [(raiz, True)]
while pila:
v, es_raiz = pila.pop()
trie += 1
if es_raiz or v.fin or len(v.hijos) != 1:
radix += 1
pila.extend((h, False) for h in v.hijos.values())
return trie, radix
rnd = random.Random(4)
silabas = ["ro", "ma", "ne", "bu", "ri", "co", "un", "ul", "us", "an", "bi", "ce", "do", "la", "mi"]
claves = sorted({"".join(rnd.choice(silabas) for _ in range(rnd.randint(2, 5))) for _ in range(3000)})
raiz = Nodo()
for k in claves:
insertar(raiz, k)
conjunto = set(claves)
for _ in range(500): # contraste con un set y con un filtro por prefijo
q = "".join(rnd.choice(silabas) for _ in range(rnd.randint(1, 3)))[: rnd.randint(1, 6)]
assert con_prefijo(raiz, q) == [k for k in claves if k.startswith(q)]
nodo = descender(raiz, q)
assert (nodo is not None and nodo.fin) == (q in conjunto)
caracteres = sum(len(k) for k in claves)
nt, nr = contar(raiz)
print(f"{len(claves)} claves, {caracteres} caracteres: trie {nt} nodos (cota {caracteres + 1}), radix {nr} nodos (cota 2n = {2 * len(claves)})")
print(f"con 256 punteros de 8 bytes por nodo, el trie ocuparía {nt * 256 * 8 / 2**20:.1f} MiB; con un dict por nodo, solo las aristas que existen")
# ---------- función de prefijos y KMP ----------
def funcion_prefijos(p):
pi, k = [0] * len(p), 0
for i in range(1, len(p)):
while k and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def kmp(t, p):
"""Posiciones de todas las ocurrencias y número de comparaciones de caracteres."""
pi, k, comps, ocurrencias = funcion_prefijos(p), 0, 0, []
for i, c in enumerate(t):
while True:
comps += 1
if c == p[k]:
k += 1
break
if k == 0:
break
k = pi[k - 1]
if k == len(p):
ocurrencias.append(i - len(p) + 1)
k = pi[k - 1]
return ocurrencias, comps
def fuerza_bruta(t, p):
comps, ocurrencias = 0, []
for s in range(len(t) - len(p) + 1):
j = 0
while j < len(p):
comps += 1
if t[s + j] != p[j]:
break
j += 1
if j == len(p):
ocurrencias.append(s)
return ocurrencias, comps
print("pi('abababca') =", funcion_prefijos("abababca"))
for _ in range(300):
t = "".join(rnd.choice("ab") for _ in range(rnd.randint(0, 40)))
p = "".join(rnd.choice("ab") for _ in range(rnd.randint(1, 6)))
oc, c = kmp(t, p)
assert oc == fuerza_bruta(t, p)[0] and c <= 2 * len(t)
n, m = 1000, 500
t, p = "a" * n, "a" * (m - 1) + "b"
print(f"t = a^{n}, p = a^{m - 1}b: fuerza bruta {fuerza_bruta(t, p)[1]} comparaciones (= (n-m+1)m = {(n - m + 1) * m}); KMP {kmp(t, p)[1]} (cota 2n = {2 * n})")
# ---------- Rabin-Karp con base aleatoria ----------
P61 = (1 << 61) - 1
def rabin_karp(t, p, mod=P61, base=None, rng=random):
"""Devuelve (ocurrencias, falsos positivos). Verifica cada coincidencia de hash carácter a carácter."""
n, m = len(t), len(p)
if m > n:
return [], 0
if base is None:
base = rng.randrange(mod)
alto = pow(base, m - 1, mod)
hp = ht = 0
for i in range(m):
hp = (hp * base + ord(p[i])) % mod
ht = (ht * base + ord(t[i])) % mod
ocurrencias, falsos = [], 0
for s in range(n - m + 1):
if ht == hp:
if t[s:s + m] == p:
ocurrencias.append(s)
else:
falsos += 1
if s + m < n:
ht = ((ht - ord(t[s]) * alto) * base + ord(t[s + m])) % mod
return ocurrencias, falsos
rnd = random.Random(5)
t = "".join(rnd.choice("ab") for _ in range(3000))
p = "abbabbab"
assert rabin_karp(t, p, rng=rnd)[0] == fuerza_bruta(t, p)[0]
print(f"módulo 2^61-1: {rabin_karp(t, p, rng=rnd)[1]} falsos positivos")
for mod in (101, 1009):
medias = sum(rabin_karp(t, p, mod=mod, rng=rnd)[1] for _ in range(100)) / 100
cota = (len(t) - len(p) + 1) * (len(p) - 1) / mod
print(f"módulo {mod}: media de falsos positivos con 100 bases aleatorias = {medias:.1f}; cota (n-m+1)(m-1)/p = {cota:.1f}")Watch four findings. The trie has far fewer nodes than the bound because syllables repeat, and the radix tree stays below . KMP meets on every random case and makes about comparisons on brute force’s worst case, versus . With there are no false positives; for small , the average over random bases stays below the theoretical bound. This is a worst-case guarantee with slack: here the per-window bound is , whereas a random fingerprint would collide with probability .
The next cell implements Aho-Corasick and tests it against the definition on hundreds of random cases, including patterns that are suffixes or substrings of one another. These expose implementations missing output links.
import random
from collections import deque
class AhoCorasick:
"""Autómata de Aho-Corasick: trie + enlaces de fallo (BFS) + enlaces de salida."""
def __init__(self, patrones):
self.patrones = list(patrones)
self.hijos = [{}] # hijos[v][c] = nodo hijo
self.fallo = [0] # fallo[v] = nodo del sufijo propio más largo que es prefijo de algún patrón
self.salida = [-1] # salida[v] = primer nodo terminal en la cadena de fallos de v (-1 si no hay)
self.fin = [[]] # fin[v] = índices de los patrones que terminan exactamente en v
self.texto = [""] # cadena de cada nodo (solo para depurar)
for i, p in enumerate(self.patrones):
v = 0
for c in p:
if c not in self.hijos[v]:
self.hijos[v][c] = len(self.hijos)
self.hijos.append({}); self.fallo.append(0); self.salida.append(-1); self.fin.append([])
self.texto.append(self.texto[v] + c)
v = self.hijos[v][c]
self.fin[v].append(i)
cola = deque(self.hijos[0].values()) # los hijos de la raíz tienen fallo 0
while cola:
u = cola.popleft()
f = self.fallo[u] # ya calculado: pertenece a un nivel menos profundo
self.salida[u] = f if self.fin[f] else self.salida[f]
for c, v in self.hijos[u].items():
f = self.fallo[u]
while f and c not in self.hijos[f]: # sube por la cadena de fallos hasta un nodo con hijo c
f = self.fallo[f]
self.fallo[v] = self.hijos[f].get(c, 0)
cola.append(v)
def buscar(self, texto):
"""Todas las ocurrencias como (inicio, índice de patrón). Tiempo O(n + z)."""
s, res = 0, []
for i, c in enumerate(texto):
while s and c not in self.hijos[s]:
s = self.fallo[s]
s = self.hijos[s].get(c, 0)
v = s if self.fin[s] else self.salida[s]
while v > 0:
for p in self.fin[v]:
res.append((i - len(self.patrones[p]) + 1, p))
v = self.salida[v]
return res
def completo(self, alfabeto):
"""Autómata determinista completo: delta[v][c] para todo símbolo. Cada carácter cuesta exactamente un paso."""
delta = [dict() for _ in self.hijos]
cola = deque([0])
while cola:
v = cola.popleft()
for c in alfabeto:
if c in self.hijos[v]:
delta[v][c] = self.hijos[v][c]
cola.append(self.hijos[v][c])
else:
delta[v][c] = delta[self.fallo[v]][c] if v else 0
return delta
ac = AhoCorasick(["he", "she", "his", "hers"])
print("nodo cadena fallo salida")
for v in range(len(ac.hijos)):
print(f"{v:4d} {ac.texto[v] or 'ε':6s} {ac.texto[ac.fallo[v]] or 'ε':5s} {ac.texto[ac.salida[v]] if ac.salida[v] > 0 else '-'}")
print("ushers ->", [(i, ac.patrones[p]) for i, p in ac.buscar("ushers")])
def por_definicion(patrones, t):
return sorted((s, i) for i, p in enumerate(patrones) for s in range(len(t) - len(p) + 1) if t.startswith(p, s))
rnd = random.Random(2)
for _ in range(400): # contraste con la definición, con patrones que son sufijos y subcadenas unos de otros
pats = list({"".join(rnd.choice("ab") for _ in range(rnd.randint(1, 5))) for _ in range(rnd.randint(1, 6))})
t = "".join(rnd.choice("ab") for _ in range(rnd.randint(0, 40)))
a = AhoCorasick(pats)
assert sorted(a.buscar(t)) == por_definicion(pats, t)
delta, s, n_ocurr = a.completo("ab"), 0, 0
for c in t: # recorrido con el autómata completo: un paso por carácter
s = delta[s][c]
v = s if a.fin[s] else a.salida[s]
while v > 0:
n_ocurr += len(a.fin[v]); v = a.salida[v]
assert n_ocurr == len(a.buscar(t))
print("400 casos aleatorios: coincide con la definición, también con el autómata completo")The printed table matches the interactive: node she has failure he and, since he is pattern-terminal, output he too. On ushers, the automaton emits she and he ending at the same position, plus hers. Next comes a realistic scanner: hundreds of signatures, including dangerous calls, credential prefixes and synthetic filler signatures, over a pseudocode corpus with injected matches. Compare the automaton with one str.find pass per signature and a re alternation, checking that all three find the same positions.
import random, re, time
reales = ["eval(", "exec(", "os.system(", "pickle.loads(", "yaml.load(", "subprocess.call(", "strcpy(", "AKIA", "ghp_", "xoxb-", "sk_live_", "-----BEGIN RSA PRIVATE KEY-----"]
def firmas(k, rnd):
extra = ["fn_%06x(" % rnd.randrange(1 << 24) for _ in range(max(0, k - len(reales)))]
return reales[:k] + extra
def corpus(n_car, rnd, sigs):
vocab = ["def ", "return ", "x = ", "foo(", "bar", "baz", "import ", "for i in range(", "):\n ", "if ", " == ", "else:\n", "data", "[0]", "len(", "self.", "#", "\n"]
partes, tam = [], 0
while tam < n_car:
s = rnd.choice(sigs) if rnd.random() < 0.01 else rnd.choice(vocab)
partes.append(s)
tam += len(s)
return "".join(partes)
def con_find(sigs, t):
pos = set()
for s in sigs:
i = t.find(s)
while i >= 0:
pos.add(i)
i = t.find(s, i + 1)
return pos
def con_re(sigs, t):
pat = re.compile("(?=(" + "|".join(re.escape(s) for s in sorted(sigs, key=len, reverse=True)) + "))")
return {m.start() for m in pat.finditer(t)}
rnd = random.Random(11)
print(f"{'firmas':>7} {'AC construir':>13} {'AC escanear':>12} {'find x k':>10} {'re':>9} {'posiciones':>10}")
medidas = []
for k in (12, 100, 400, 1500):
sigs = firmas(k, rnd)
t = corpus(200_000, rnd, sigs)
t0 = time.perf_counter(); ac = AhoCorasick(sigs); t1 = time.perf_counter()
pos_ac = {i for i, p in ac.buscar(t)}; t2 = time.perf_counter()
pos_f = con_find(sigs, t); t3 = time.perf_counter()
pos_r = con_re(sigs, t) if k <= 100 else None; t4 = time.perf_counter()
assert pos_ac == pos_f and (pos_r is None or pos_r == pos_ac)
medidas.append((k, t2 - t1, t3 - t2))
re_txt = f"{1000 * (t4 - t3):7.1f}ms" if pos_r is not None else " -"
print(f"{k:7d} {1000 * (t1 - t0):11.1f}ms {1000 * (t2 - t1):10.1f}ms {1000 * (t3 - t2):8.1f}ms {re_txt} {len(pos_ac):10d}")
k, t_ac, t_find = medidas[-1]
print(f"\ncon {k} firmas, el bucle de find cuesta ≈ {1e6 * t_find / k:.0f} µs por firma; el autómata, {1e3 * t_ac:.0f} ms para todas")
print("el cruce se da hacia las", round(t_ac / (t_find / k)), "firmas: antes gana find (C puro), después el autómata (su tiempo no depende de k)")Two lessons emerge. First, an honest limitation: in Python, the automaton pays interpreter overhead through a Python loop per character, whereas str.find runs in C. With few signatures, find wins. Second, curve shape: Aho-Corasick’s scanning time stays almost constant from 12 to 1500 signatures; only construction grows slightly. find and re time grow with . A compiled production engine, such as Rust’s aho-corasick crate used by ripgrep and other tools, or Hyperscan, moves the crossover down to a few signatures.
A linear regular expression engine
The second lab builds both engines over the same Thompson NFA for a syntax subset: literals, ., |, *, +, ? and parentheses. One simulates the active-state set; the other backtracks and counts visits. Both are checked against re.fullmatch on 150 random expressions and every string over up to length .
import random, re, itertools
# ---------- sintaxis: literales, ., |, *, +, ?, paréntesis ----------
def parsear(src):
pos = 0
def alt():
nonlocal pos
r = cat()
while pos < len(src) and src[pos] == "|":
pos += 1
r = ("alt", r, cat())
return r
def cat():
nonlocal pos
r = ("eps",)
while pos < len(src) and src[pos] not in "|)":
r = rep() if r == ("eps",) else ("cat", r, rep())
return r
def rep():
nonlocal pos
r = atomo()
while pos < len(src) and src[pos] in "*+?":
r = ({"*": "star", "+": "plus", "?": "opt"}[src[pos]], r)
pos += 1
return r
def atomo():
nonlocal pos
c = src[pos]
pos += 1
if c == "(":
r = alt()
assert src[pos] == ")", "falta )"
pos += 1
return r
return ("any",) if c == "." else ("lit", c)
r = alt()
assert pos == len(src), "sobra )"
return r
# ---------- construcción de Thompson: un estado por literal y uno por bifurcación ----------
class NFA:
def __init__(self, ast):
self.est = [] # ('c', símbolo o None, sig) | ('s', sig1, sig2, es_bucle) | ('m',)
self.fin = self._nuevo(("m",))
self.ini = self._construir(ast, self.fin)
def _nuevo(self, e):
self.est.append(e)
return len(self.est) - 1
def _construir(self, r, sig):
t = r[0]
if t == "eps":
return sig
if t == "lit":
return self._nuevo(("c", r[1], sig))
if t == "any":
return self._nuevo(("c", None, sig))
if t == "cat":
return self._construir(r[1], self._construir(r[2], sig))
if t == "alt":
return self._nuevo(("s", self._construir(r[1], sig), self._construir(r[2], sig), False))
if t == "opt":
return self._nuevo(("s", self._construir(r[1], sig), sig, False))
s = self._nuevo(None) # star / plus: la bifurcación vuelve al cuerpo o sale
cuerpo = self._construir(r[1], s)
self.est[s] = ("s", cuerpo, sig, True)
return s if t == "star" else cuerpo
def cierre(nfa, semillas):
visto, pila, res = set(), list(semillas), set()
while pila:
s = pila.pop()
if s in visto:
continue
visto.add(s)
e = nfa.est[s]
if e[0] == "s":
pila.extend((e[1], e[2]))
else:
res.add(s)
return res
def simular(nfa, texto):
"""Simulación del NFA (Thompson, 1968): O(n m) en el peor caso. Devuelve (acepta, estados examinados)."""
activos, trabajo = cierre(nfa, [nfa.ini]), 0
for c in texto:
trabajo += len(activos)
activos = cierre(nfa, [nfa.est[s][2] for s in activos if nfa.est[s][0] == "c" and nfa.est[s][1] in (None, c)])
return nfa.fin in activos, trabajo + len(activos)
def retroceso(nfa, texto, tope=10**7):
"""Motor con retroceso sobre el mismo NFA. Cuenta visitas (estado, posición); None si supera el tope."""
visitas, en_pila, n = 0, {}, len(texto)
class Tope(Exception):
pass
def dfs(s, i):
nonlocal visitas
visitas += 1
if visitas > tope:
raise Tope
e = nfa.est[s]
if e[0] == "m":
return i == n
if e[0] == "c":
return i < n and e[1] in (None, texto[i]) and dfs(e[2], i + 1)
if not e[3]:
return dfs(e[1], i) or dfs(e[2], i)
if en_pila.get(s) == i: # iteración vacía: se rechaza, como hacen los motores reales
return False
previo = en_pila.get(s)
en_pila[s] = i
r = dfs(e[1], i)
en_pila[s] = previo
return r or dfs(e[2], i)
try:
return dfs(nfa.ini, 0), visitas
except Tope:
return None, visitas
# ---------- verificación frente a re, con todas las cadenas sobre {a, b} de longitud <= 6 ----------
def aleatoria(rnd, d):
if d == 0 or rnd.random() < 0.25:
return rnd.choice("ab.")
t = rnd.choice(["cat", "alt", "star", "plus", "opt"])
if t == "cat":
return aleatoria(rnd, d - 1) + aleatoria(rnd, d - 1)
if t == "alt":
return "(" + aleatoria(rnd, d - 1) + "|" + aleatoria(rnd, d - 1) + ")"
return "(" + aleatoria(rnd, d - 1) + ")" + {"star": "*", "plus": "+", "opt": "?"}[t]
cadenas = [""]
for L in range(1, 7):
cadenas += ["".join(c) for c in itertools.product("ab", repeat=L)]
rnd = random.Random(3)
n_pruebas = 0
for _ in range(150):
r = aleatoria(rnd, 3)
nfa = NFA(parsear(r))
comp = re.compile(r)
for s in cadenas:
esperado = comp.fullmatch(s) is not None
assert simular(nfa, s)[0] == esperado, (r, s)
assert retroceso(nfa, s)[0] == esperado, (r, s)
n_pruebas += 1
print(f"{n_pruebas} pares (expresión, cadena) coinciden con re.fullmatch, con la simulación y con el retroceso")With the engine verified, measure backtracking visits and simulation work for (a+)+b on , alongside re’s runtime on the same input and NFA-simulation runtime on very long strings.
import time
nfa = NFA(parsear("(a+)+b"))
seguro = NFA(parsear("a+b"))
print(f"{'n':>6} {'retroceso (visitas)':>20} {'5*2^n-4':>10} {'NFA (examinados)':>17} {'re.fullmatch':>13}")
for n in (8, 12, 16, 18, 20):
s = "a" * n
if n <= 18:
acepta, v = retroceso(nfa, s)
assert not acepta and v == 5 * 2 ** n - 4
else:
v = None
ok, trabajo = simular(nfa, s)
t0 = time.perf_counter(); re.fullmatch("(a+)+b", s); dt = time.perf_counter() - t0
assert not ok
vis = f"{v:20d}" if v is not None else f"{'(no se ejecuta)':>20}"
print(f"{n:6d} {vis} {5 * 2 ** n - 4:10d} {trabajo:17d} {1000 * dt:11.1f}ms")
for n in (2000, 20000):
s = "a" * n
t0 = time.perf_counter(); ok, trabajo = simular(nfa, s); dt = time.perf_counter() - t0
print(f"{n:6d} {'(inviable)':>20} {'':>10} {trabajo:17d} {1000 * dt:11.1f}ms <- simulación del NFA, no re")
print("reescritura a+b sobre a^20:", retroceso(seguro, "a" * 20)[1], "visitas del retroceso;", simular(seguro, "a" * 20)[1], "estados examinados")Backtracking makes exactly visits: every extra character doubles the work. Simulation examines states. The optimized backtracking engine re doubles its time with each extra : between and it grows from a tenth of a millisecond to tens of milliseconds. Forty characters would take roughly a day, another twenty doublings, a factor of . Our pure-Python NFA simulation handles twenty thousand characters without difficulty: this is the behavior guaranteed by RE2 and the regex crate.
Typical errors
Exercises
while k > 0 and P[i] != P[k]: k = pi[k-1], and then if P[i] == P[k]: k += 1; pi[i] = k) performs at most different character comparisons (the one that closes the while and the one of the if compare the same pair and count as one).Step 1 of 4. What is at the end of iteration as a function of at the end of iteration and the failures within the while loop?
funcion_prefijos(s), which returns the list pi with pi[i] = length of the longest proper border of s[:i+1], and which must use only indexing and comparisons == or != between elements (the tests count the comparisons and require a linear cost). Use it to implement periodo_minimo(s): the smallest such that s[j] == s[j + p] for every valid (if there is no smaller period, it is len(s); for the empty string, 0). Hint from theory: . The initial code calculates in quadratic time and does not know how to compute the period.def funcion_prefijos(s):
"""pi[i] = longitud del borde propio más largo de s[:i+1]."""
n = len(s)
pi = [0] * n
for i in range(1, n):
# versión ingenua: prueba todos los bordes posibles, del mayor al menor (cuadrática)
for k in range(i, 0, -1):
if s[:k] == s[i + 1 - k:i + 1]:
pi[i] = k
break
return pi
def periodo_minimo(s):
"""Menor p >= 1 con s[j] == s[j + p] para todo j válido; len(s) si no hay periodo menor; 0 para ''."""
return len(s)re with fullmatch) evaluates (i) (\d+)*, (ii) (a|a?)+, (iii) [a-z]+@[a-z]+\.com, and (iv) (a|b)*c are evaluated on hostile strings that almost match (for example, a long series of digits and an invalid character at the end). Which ones are vulnerable to exponential backtracking?Summary
- A trie of keys totaling characters has nodes and supports membership and prefix queries in . A radix tree, with nodes, is the version used in routing tables and prefix caches. Allocating pointers per node is the typical memory mistake.
- The prefix function gives each pattern prefix’s longest border. After a mismatch, shift the pattern by without moving backward in the text. With potential , KMP makes comparisons and computing costs .
- Rabin-Karp compares rolling polynomial hashes and verifies candidate matches. A prime modulus and uniform base give collision probability for distinct strings. With a fixed base or modulus , an adversary can construct collisions.
- Aho-Corasick adds failure links, computed by BFS with KMP’s amortized analysis, and output links to the trie. It finds every occurrence of every pattern in one pass taking . It is the DFA for ‘ends with some pattern’, with states.
- A backtracking engine can cost :
(a+)+bon makes exactly visits in this lesson’s engine. Thompson NFA simulation always costs . Defending against ReDoS requires a linear-time engine such as RE2 or Rust’sregex, unambiguous expressions, input limits and process isolation. A timer on the same thread is insufficient.