Module contents
Lesson 12 of 33Core 110 min

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 ww, 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 qq, then traverse the subtree rooted there; it contains exactly the keys beginning with qq.
Proof

Each key contributes at most ∣w∣\abs{w} new nodes, one per character, to those already present; only the root is not contributed by a character. Summing gives ≤N+1\le N + 1. 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 ℓz\ell z nodes.

∎

The bound N+1N + 1 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 4848 characters and their trie has 2828 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 σ\sigma.

RepresentationNode spaceSon by symbolNotes
Array of σ\sigma pointersΘ(σ)\Theta(\sigma)O(1)\bigO(1)With σ=256\sigma = 256 and 8-byte pointers, 2 KiB per node even if it has a child
Hash table (dict)O(children)\bigO(\text{children})O(1)\bigO(1) expectedThe usual in Python; with overloading by input
List of symbol and pointer pairsO(children)\bigO(\text{children})O(σ)\bigO(\sigma)Compact; good if the nodes have few children
Symbol search treeO(children)\bigO(\text{children})O(log⁡σ)\bigO(\log \sigma)Free alphabetical order: Bentley and Sedgewick’s ternary trie

The array representation causes the most common memory mistake. By the proposition, 10510^5 keys of length 12 have at most 1.2⋅106+11.2 \cdot 10^6 + 1 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 22 to 2.52.5 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 LL leaves, I1I_1 internal nodes with one child, and I2I_2 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 L+I1≤nL + I_1 \le n. To bound I2I_2, count edges. Their number is the number of nodes minus one, L+I1+I2L + I_1 + I_2, and also the sum of all child counts, which is at least 2I2+I1+12 I_2 + I_1 + 1: branching nodes contribute at least two, single-child nodes contribute one, and the root contributes at least one since n≥1n \ge 1. From L+I1+I2≥2I2+I1+1L + I_1 + I_2 \ge 2I_2 + I_1 + 1 we obtain I2≤L−1I_2 \le L - 1. Total node count is therefore 1+(L+I1)+I2≤1+n+(L−1)≤n+L≤2n1 + (L + I_1) + I_2 \le 1 + n + (L - 1) \le n + L \le 2n. Each label stored as a key-start-length triple takes three words, and there are fewer than 2n2n edges.

∎

The bound is tight: the seven Latin-script keys in the interactive example give exactly 2n=142n = 14 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 O(∣w∣)\bigO(\abs{w}). Visited-node count falls from ∣w∣+1\abs{w} + 1 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.

InteractiveTrie and radix tree of the same keys
romaneusulusubensriconundusεromaneromanusromulusrubensruberrubiconrubicundus
  • end of key
  • prefix traversal
  • no match
2 keys with the prefix «rubi»: rubicon, rubicundus.
Example
Structure
nn7
Characters ∑∣w∣\sum \lvert w \rvert48
Trie nodes28
Radix nodes14
Radix bound 2n2n14
Visited nodes5
Array of 256 pointers56.0 KiB
Seven Latin keys (48 characters): the trie has 28 nodes and the radix tree, 14 = 2n, the theorem bound. Switch between the two structures with the same prefix and check that the path is the same: in the radix tree it can end in the middle of an edge. Change to the example «Functions» to see the shared beginnings of a signature scanner, or to the «Bits» example to see how a routing table is a binary trie. At the end of the readings column, the memory that would be occupied by the array of 256 pointers per node: the radix tree halves it here, and to much less in real dictionaries.

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 T[0..n)T[0..n) and pattern P[0..m)P[0..m), find every position ss satisfying T[s..s+m)=PT[s..s+m) = P. The direct method aligns the pattern at every ss and compares until the first mismatch. It is correct but costs Θ(nm)\Theta(nm) in the worst case: with T=anT = a^n and P=am−1bP = a^{m-1}b, each alignment compares mm characters before failing on the last, for (n−m+1) m(n-m+1)\,m comparisons in total. With n=106n = 10^6 and m=103m = 10^3, that is 10910^9 comparisons merely to report no matches.

The waste lies in what the method discards. When comparison fails at pattern position kk, the preceding kk text characters are already known to equal P[0..k)P[0..k). Brute force forgets this, resets the text pointer to s+1s + 1 and rereads them. KMP reuses what was already read.

Borders and the prefix function

For P=abababcaP = abababca, suppose the text matches abababababab and then fails at cc. The matched string is abababababab; the next possible alignment starts where a suffix of that string matches a prefix of the pattern. Suffix abababab is also a pattern prefix, so comparison can continue at position 44 without rereading text.

For P=abababcaP = abababca, π=[0,0,1,2,3,4,0,1]\pi = [0, 0, 1, 2, 3, 4, 0, 1]: after matching abababababab, so k=6k = 6, the longest border has length π[5]=4\pi[5] = 4. A fact about borders lets us traverse all of them.

Proof

If vv is a border of u[0..b)u[0..b), it is a suffix of u[0..b)u[0..b), itself a suffix of uu, so vv is a suffix of uu. It is also a prefix of u[0..b)u[0..b), itself a prefix of uu, so it is a prefix of uu. Hence vv is a border of uu. Conversely, let vv be a border of uu with ∣v∣<b\abs{v} < b. Both vv and the border ww of length bb are suffixes of uu, and ∣v∣<∣w∣\abs{v} < \abs{w}, so vv is a suffix of ww. Both are prefixes of uu, so vv is a prefix of ww. Thus vv is a border of ww.

∎

The algorithm and interactive visualization

With state kk equal to the number of pattern characters matched against the end of the text read so far, KMP needs one state variable: if T[i]=P[k]T[i] = P[k], advance ii and kk; otherwise, if k>0k > 0, replace kk by π[k−1]\pi[k-1] without moving ii; if k=0k = 0, advance ii. When kk reaches mm, record a match and continue with k=π[m−1]k = \pi[m-1]. The whole pattern has borders too, allowing overlapping matches.

InteractiveKMP shifts
Text Ta0b1a2b3a4b5a6b7a8b9c10a11b12a13b14a15b16c17a18abababcaP shifted by 0Pattern and prefix functiona00b01a12b23a34b45c06a17πCurrent border length k (the potential) at each comparison
  • match
  • mismatch
  • longest border (not compared again)
  • next alignment
comparison 1 / 21
T[0]=P[0]=T[0] = P[0] = matches a: they match. Both pointers advance (kk goes from 0 to 1).
Mode
Example
Position ii of the text0
Matched length kk0
Comparisons1
Bound 2n2n38
Brute force (total)44
KMP (total)21
The pattern (central row) is aligned with the text at position i - k. If the comparison fails, the dashed outline shows the next alignment, which is not the immediate one but the one that respects the longest border of what has already been matched (in violet, the k' = π[k-1] characters that need not be compared again). With 'Borders', KMP makes 21 comparisons against 44 of brute force. With 'aaa...ab' (n = 26, m = 6), 47 against 126. In 'Calculating π' it is seen how the same machine builds the table by comparing the pattern with itself. Below, the length k in each comparison: it goes up by one at a time and drops in jumps, and that's why the total does not exceed 2n.

Correctness follows from one question: after a mismatch with kk matched characters, which alignments can we discard without inspecting them?

Proof

If s+ds + d were a match with 0<d<k−π[k−1]0 < d < k - \pi[k-1], the text T[s+d..s+k)T[s+d..s+k) would equal both P[d..k)P[d..k) under alignment ss and P[0..k−d)P[0..k-d) under alignment s+ds+d. Consequently P[0..k−d)P[0..k-d) would be a border of P[0..k)P[0..k) of length k−d>π[k−1]k - d > \pi[k-1], contradicting the maximality of π[k−1]\pi[k-1]. For d=k−π[k−1]d = k - \pi[k-1], the border of length π[k−1]\pi[k-1] equals T[s+d..s+k)T[s+d..s+k) by definition, so that alignment is consistent with the kk characters already read. If π[k−1]=0\pi[k-1] = 0, there is no border and the algorithm jumps to alignment s+ks + k.

∎

If the new k′=π[k−1]k' = \pi[k-1] also mismatches, repeat the argument with k′k'. 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 π\pi using the same loop with T=P[1..m)T = P[1..m) and pattern PP: π[i]\pi[i] is the value of kk reached after reading P[i]P[i]. This is the interactive’s ‘Compute π’ mode, and explains why preprocessing and searching share the same analysis.

Proof

Apply the potential method with Φ=k≥0\Phi = k \ge 0, initially 00. Each comparison does one of three things. On a match, ii and kk both increase by one: actual cost 11 and ΔΦ=+1\Delta\Phi = +1. A mismatch with k=0k = 0 increases ii and leaves Φ\Phi unchanged. A mismatch with k>0k > 0 replaces kk by π[k−1]<k\pi[k-1] < k, so ΔΦ≤−1\Delta\Phi \le -1. At most nn comparisons increase ii, because the text is read once. Comparisons decreasing kk cannot outnumber the increases of kk, and there are at most nn of those: kk increases only when ii advances and never becomes negative. Total comparisons: ≤n+n=2n\le n + n = 2n.

∎

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 π\pi is the lesson’s first exercise. The text pointer ii 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 kk.

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 O(1)\bigO(1).

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 D(x)=∑j=0m−1(uj−vj) xm−1−jD(x) = \sum_{j=0}^{m-1} (u_j - v_j)\, x^{m-1-j}, a polynomial over the field Fp\mathbb{F}_p. A collision occurs exactly when D(b)=0D(b) = 0. Since u≠vu \ne v and symbols are smaller than pp, some coefficient is nonzero, so DD is not the zero polynomial. Its degree is at most m−1m-1, giving at most m−1m-1 roots in Fp\mathbb{F}_p. Of the pp possible values of bb, at most m−1m-1 are roots. The second claim follows by linearity of expectation, summing over the n−m+1n-m+1 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 {Hb}\{H_b\} is almost universal with ε=(m−1)/p\varepsilon = (m-1)/p. Second, with the Mersenne prime p=261−1p = 2^{61} - 1, whose modular reduction takes only a few operations, and n=106n = 10^6 and m=103m = 10^3, expected false positives are fewer than 4.4⋅10−104.4 \cdot 10^{-10}. Verifying each genuine match costs O(m)\bigO(m), giving expected total time O(n+m+occ⋅m)\bigO(n + m + \mathrm{occ}\cdot m).

InteractiveThe rolling hash of Rabin-Karp
Text and current windowabracadabra␣abracadabra␣cadabraHash of the window that starts at each position66315117631216631511763311651176
  • actual match
  • false positive (hash equal, text different)
  • window discarded by the hash
window 0 / 27
Window 0: "abra". The hash matches H(P)=6H(P) = 6 and upon character-by-character verification, it is a real occurrence.
Update in O(1)\bigO(1) with bm−1 mod p=8b^{m-1} \bmod p = 8: h1=((6−2⋅8)⋅5+4) mod 13=6h_{1} = \big((6 - 2\cdot 8)\cdot 5 + 4\big) \bmod 13 = 6
5
Hash of the pattern H(P)H(P)6
Windows28
Real occurrences5
False positives (this base)3
Mean false positives (all bases)2.23
Mean bound5.31
Each cell in the lower band is the hash of the window that starts at that position. With p = 13 there are many false positives (red), because each window different from the pattern can collide with a probability of up to (m - 1)/p = 3/13; increase p and they disappear. Click 'Random base': the number of false positives changes with the base, but their exact mean over the p possible bases (the theorem's expectation) never exceeds the bound of (m - 1)/p per window different from the pattern. Below the text, the arithmetic update of the current window with its real numbers.

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 kk patterns in a hash table and query each window’s hash. Expected time is O(n+km)\bigO(n + km) plus O(m)\bigO(m) per candidate match requiring verification, so kk affects only preprocessing. Expected false positives rise to at most (n−m+1) k (m−1)/p(n-m+1)\,k\,(m-1)/p, negligible with p=261−1p = 2^{61}-1. 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 kk patterns with kk KMP passes costs O(kn+M)\bigO(kn + M), where M=∑i∣Pi∣M = \sum_i \abs{P_i}. Aho and Corasick (1975), working on bibliographic search, showed how to do it in O(n+M+z)\bigO(n + M + z), with zz reported occurrences. Their idea generalizes KMP using the patterns’ trie as its skeleton.

After reading T[0..i]T[0..i], 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 π\pi.

Proof

Induct on ii. Suppose the state before reading c=T[i]c = T[i] was vv, the longest suffix of T[0..i−1]T[0..i-1] that is a prefix. Suffixes of T[0..i]T[0..i] that are pattern prefixes have the form x cx\,c, where xx is a suffix of T[0..i−1]T[0..i-1] that is a prefix and x cx\,c is also a prefix. The candidates for xx are str⁡(v)\operatorname{str}(v) and those suffixes of str⁡(v)\operatorname{str}(v) represented by trie nodes: the chain v,f(v),f(f(v)),…v, f(v), f(f(v)), \dots, 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 cc child, giving the longest suffix. If none has one, only the empty suffix remains, represented by the root. For outputs, a pattern ends at ii exactly when it is a suffix of T[0..i]T[0..i]. Every pattern suffix of T[0..i]T[0..i] is itself a prefix, so its node lies along v,f(v),…v, f(v), \dots. Output links skip precisely to the terminal nodes.

∎

Build failure links level by level using breadth-first search. Root children fail to the root. For a node vv reached from uu by symbol cc, with uu already processed, start at f(u)f(u) and follow failure links until reaching a node with a cc child. That child is f(v)f(v), or use the root if none exists. This is exactly the π\pi loop. Output links follow from ff: use o(v)=f(v)o(v) = f(v) if f(v)f(v) is pattern-terminal, otherwise o(f(v))o(f(v)).

InteractiveConstruct an Aho-Corasick automaton
hesheisrs012he345she67his89hers
  • trie edge
  • failure link
  • output link
  • end of pattern
node 9 / 9
Node «hers» = «her» + «s». It starts from the failure of «her» and follows the chain «ε» until a node with child «s», or the root. Result: failure of «hers» = «s».
Phase
Example
Patterns4
Sum of lengths MM12
Nodes (≤ M+1M+1)10
With the patterns he, she, his and hers (M = 12) the trie has 10 nodes and the text 'ushers' emits three matches, two of which end at the same position. In 'Construct', each step fixes the failure link of a node in breadth-first order and shows the failure chain that is traversed. In 'Scan', the state jumps with each character: reading 'r' from 'she' follows a failure to 'he' and enters 'her'. The orange dotted link from 'she' to 'he' is what allows emitting the two patterns when reading the 'e'. Test the example 'Signatures' (names of dangerous functions, like those of a code scanner) or write your own.
Proof

Scanning. Let did_i be state depth after reading T[i]T[i]. Reading a character increases depth by at most one; each failure jump decreases it by at least one. Since d≥0d \ge 0, jumps cannot outnumber the at most ≤n\le n increases. Each step along an output-link chain emits an occurrence, giving O(z)\bigO(z) total output work. Construction. Let PjP_j be a pattern and v1,…,v∣Pj∣v_1, \dots, v_{\abs{P_j}} the nodes along its path. Searching for the failure of vt+1v_{t+1} starts at f(vt)f(v_t). The lemma gives prof⁡(f(vt+1))≤prof⁡(f(vt))+1\operatorname{prof}(f(v_{t+1})) \le \operatorname{prof}(f(v_t)) + 1, while each failure-chain step decreases depth by at least one. The same amortized argument as KMP gives O(∣Pj∣)\bigO(\abs{P_j}) per pattern and O(M)\bigO(M) 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: δ(v,c)=\delta(v, c) = the cc child of vv when present, otherwise δ(f(v),c)\delta(f(v), c), with missing root transitions returning to the root. The same BFS builds a deterministic finite automaton with ≤M+1\le M + 1 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 Σ∗(P1∣⋯∣Pk)\Sigma^*(P_1 | \cdots | P_k), a trie with a root loop, has at most M+1M + 1 states, and subset construction could produce 2M2^{M}, but only M+1M + 1 are reachable here because the longest suffix determines each reachable subset, as the invariant lemma shows. The complete table’s cost is memory, Θ(Mσ)\Theta(M\sigma), 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 rr into an NFA with m=O(∣r∣)m = \bigO(\abs{r}) states: one per literal, plus branching states for |, *, + and ?. To test membership of a length-nn string, maintain the set of active states and advance one character at a time. There are never more than mm active states, giving O(nm)\bigO(nm) time and O(m)\bigO(m) memory for every expression and every input. Cache visited sets as DFA states, constructing only those needed, a lazy DFA, and each character costs O(1)\bigO(1) 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 2n2^n

Consider (a+)+b on ana^n, without a final bb. Each aa can continue the current a+a+ block or start a new block. The engine does not discover that there is no bb until the end, so it must try every partition of ana^n into blocks.

Proof

Every partition of ana^n into consecutive nonempty blocks is a recognition path through (a+)+ consuming the entire string. The engine must exhaust them before concluding that no bb follows. Partitions correspond to subsets of the n−1n-1 boundaries between characters, giving 2n−12^{n-1}. For the NFA, the active-state set after every character is the same constant-sized set, containing the loop states and the bb 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.

InteractiveReDoS Explorer
A. Backtracking attempt tree (383 nodes)depth = characters consumedB. Simulation of NFA: active states after each characteraaaaaaa✓ acceptq1 bq4 aC. Steps according to n (logarithmic scale)11010010³10⁴10⁵teaching-engine limit16121824n (repetitions of the unit)
  • consume a character
  • failed attempt
  • acceptance
  • backtracking (visits)
  • NFA (states examined)
The backtracking engine rejects «aaaaaaa» after 636 visits to (state, position) pairs; the NFA simulation, after examining 15 states, with at most 3 active at once. Each character added multiplies the work by ≈ 2.00: exponential growth.
7
NFA States5
Backtracking: visits636
NFA: states examined15
Growth by character×2.00
Resultrejects
Panel A: the search tree of a backtracking engine for (a+)+b over aⁿ; each level is a character consumed, each red leaf a failure. There are exactly 5·2ⁿ − 4 visits: 636 with n = 7, and from n = 16 (327 676) the teaching engine cuts off at its limit of 3·10⁵; with n = 20 there would be more than 5·10⁶. Panel B: the simulation of the NFA with the set of active states (2n + 1 examined states). Panel C: steps according to n on a logarithmic scale; the red line is the backtracking (exponential) and the blue curve, almost flat, the simulation (linear). Test (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 aa 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 aa. If the NFA is unambiguous, recognizing every string along one path, backtracking does not explode for this reason.

Defenses. None replaces the others.

  1. Use a linear-time engine for untrusted input: RE2, Rust’s regex crate, Go’s regexp package, .NET’s NonBacktracking option and Hyperscan simulate NFAs or build DFAs on demand, guaranteeing O(nm)\bigO(nm). In exchange, they omit backreferences and some assertions.
  2. Rewrite without ambiguity: (a+)+b is equivalent to a+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.
  3. 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.
  4. Analyze expressions in the repository with static ambiguity detectors such as recheck or regexploit. Test your own expressions with increasingly long inputs and measure cost growth.

In the tools

ToolStrategyTime guarantee
grep of GNULazy DFA with prefix filtering of fixed strings; backtracking only if there are references backwardlinear without references backward
RE2 (Google) and the package regexp of GoNFA and lazy DFAlinear en nn
Crate regex of Rust (and ripgrep)Lazy DFA, NFA, and literals with Aho-Corasick and SIMDO(nm)\bigO(nm)
Hyperscan (and its derivative Vectorscan)NFA and DFA with vectorization, many expressions at once and flow modelinear, designed for thousands of rules
Module re from Python, PCRE, Java, JavaScriptbackexponential 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.

[ ]Trie, KMP and Rabin-Karp from scratchBrowser
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 N+1N+1 because syllables repeat, and the radix tree stays below 2n2n. KMP meets 2n2n on every random case and makes about 1.5 n1.5\,n comparisons on brute force’s worst case, versus (n−m+1)m=250 500(n-m+1)m = 250\,500. With p=261−1p = 2^{61}-1 there are no false positives; for small pp, the average over random bases stays below the theoretical bound. This is a worst-case guarantee with slack: here the per-window bound is (m−1)/p(m-1)/p, whereas a random fingerprint would collide with probability 1/p1/p.

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.

[ ]Aho-Corasick from scratch, with failure and output linksBrowser
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.

[ ]Signature Scanner: Aho-Corasick vs str.find and reBrowser
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 kk. 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 {a,b}\{a, b\} up to length 66.

[ ]Thompson's construction, NFA simulation and backtracking versus reBrowser
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 ana^n, alongside re’s runtime on the same input and NFA-simulation runtime on very long strings.

[ ]When re explodes and NFA simulation does notBrowser
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 5⋅2n−45 \cdot 2^n - 4 visits: every extra character doubles the work. Simulation examines 2n+12n + 1 states. The optimized backtracking engine re doubles its time with each extra aa: between n=8n = 8 and n=20n = 20 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 220≈1062^{20} \approx 10^6. 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

ProofThe calculation of π uses O(m) comparisons
Prove: Prove that the calculation of the prefix function of a pattern of length mm (the loop that keeps kk, the current border length, and for each i=1,…,m−1i = 1, \dots, m-1 executes 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 2(m−1)2(m-1) different character comparisons (the one that closes the while and the one of the if compare the same pair and count as one).
0
Let kik_i be the value of kk at the end of iteration ii (with k0=0k_0 = 0). Use Φ=k\Phi = k as potential.

Step 1 of 4. What is kk at the end of iteration ii as a function of kk at the end of iteration i−1i-1 and the failures within the while loop?

CodePrefix function and minimum period
Implement 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 p≥1p \ge 1 such that s[j] == s[j + p] for every valid jj (if there is no smaller period, it is len(s); for the empty string, 0). Hint from theory: p=n−π[n−1]p = n - \pi[n-1]. The initial code calculates π\pi 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)
Shift+Enter to run
NumericRabin-Karp collision with p = 2^61 - 1
Two distinct strings of length 10410^4 over a byte alphabet, and a base bb chosen uniformly in {0,…,p−1}\{0, \dots, p-1\} with p=261−1p = 2^{61} - 1. Bound the probability that they have the same polynomial hash modulo pp. Give the bound in units of 10−1510^{-15}.
NumericKMP comparisons over a^40
P=a7bP = a^7 b is sought in T=a40T = a^{40} with the KMP from the lesson (one character comparison per iteration; failing with k>0k > 0 moves k=π[k−1]k = \pi[k-1] without moving ii). How many character comparisons does it make?
NumericMemory of a trie with arrays of pointers
A dictionary has 10510^5 keys of 1212 byte characters (σ=256\sigma = 256). Each trie node stores an array of 256256 pointers of 88 bytes. With the node bound of the trie cost proposition, how many gigabytes (10910^9 bytes) can it occupy at most?
QuizFailure links and output links
The Aho-Corasick automaton is built with the patterns {aab, abab, bab, babb}\{aab,\ abab,\ bab,\ babb\}. What are the failure links of the nodes aabaab, abaaba, abababab, and babbbabb, and the output link of abababab?
QuizCatastrophic backtracking
A backtracking regular-expression engine (such as Python'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?
QuizWhich algorithm to choose
A network scanner must search simultaneously for 5 0005\,000 fixed signatures in a stream that cannot be stored and whose content is controlled by an attacker, with a time budget strictly linear in the stream size. What do you choose?

Summary

Key idea
Efficient pattern matching avoids reexamining known information: tries share prefixes; KMP and Aho-Corasick retain the longest suffix read so far that is a pattern prefix, using potential kk to pay O(n+z)\bigO(n + z) total cost; Rabin-Karp replaces character comparisons with fingerprints using a random base; and regex engines avoid backtracking vulnerabilities by simulating the NFA.
  • A trie of nn keys totaling NN characters has ≤N+1\le N + 1 nodes and supports membership and prefix queries in O(∣w∣)\bigO(\abs{w}). A radix tree, with ≤2n\le 2n nodes, is the version used in routing tables and prefix caches. Allocating σ\sigma pointers per node is the typical memory mistake.
  • The prefix function π\pi gives each pattern prefix’s longest border. After a mismatch, shift the pattern by k−π[k−1]k - \pi[k-1] without moving backward in the text. With potential kk, KMP makes ≤2n\le 2n comparisons and computing π\pi costs ≤2(m−1)\le 2(m-1).
  • Rabin-Karp compares rolling polynomial hashes and verifies candidate matches. A prime modulus and uniform base give collision probability ≤(m−1)/p\le (m-1)/p for distinct strings. With a fixed base or modulus 2642^{64}, 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 O(n+M+z)\bigO(n + M + z). It is the DFA for ‘ends with some pattern’, with ≤M+1\le M + 1 states.
  • A backtracking engine can cost Θ(2n)\Theta(2^n): (a+)+b on ana^n makes exactly 5⋅2n−45 \cdot 2^n - 4 visits in this lesson’s engine. Thompson NFA simulation always costs O(nm)\bigO(nm). Defending against ReDoS requires a linear-time engine such as RE2 or Rust’s regex, unambiguous expressions, input limits and process isolation. A timer on the same thread is insufficient.