Module contents
Lesson 20 of 22Core 105 min

Finite automata and regular languages

Finite automata model computation with bounded memory. This lesson develops DFAs, NFAs and the subset construction, regular expressions and Kleene's theorem, the pumping lemma and Myhill-Nerode, minimization and the Chomsky hierarchy, then builds a regular-expression engine without backtracking.

After this lesson you can

  • Design DFAs and NFAs for given languages and prove correctness by induction over the input.
  • Convert among regular expressions, NFAs and DFAs using Thompson's and subset constructions.
  • Prove that a language is not regular using the pumping lemma and Myhill-Nerode.
  • Minimize DFAs and reason about their minimum number of states.
  • Explain catastrophic backtracking and build an engine that avoids it.

Before you start

Motivation: computation with bounded memory

A program that reads a stream of symbols once, from left to right, and stores only a fixed amount of information regardless of the stream’s length is a finite automaton. It is deliberately a limited model. It is the smallest model of computation that still does useful work, and its small size lets us analyze it completely. Almost every question about finite automata, such as whether two are equivalent, whether one accepts any string, or which equivalent automaton is smallest, has an exact algorithm. For more powerful machines, as you will see in the next lesson, those questions become undecidable.

Finite automata also appear throughout computing.

  • Tokenizers and lexical analyzers. A compiler splits source code into identifiers, numbers, and operators with an automaton generated from regular expressions. Language models do something similar before BPE: a regular expression splits text into words, numbers, and punctuation. This is pretokenization.
  • Input validation. Dates, addresses, identifiers, and web application firewall filters are commonly described using regular expressions.
  • Constrained decoding. To make an LLM output only strings in a format such as a JSON schema, a date, or a function call, compile the format to an automaton and rule out tokens that cannot extend a valid prefix at every step. This is the idea of Willard and Louf (2023), which you will study as constrained decoding.
  • Sequence models. An nn-gram model is a probabilistic finite automaton whose state is the last n−1n - 1 tokens, as in the n-gram Markov assumption.

There is also a security reason to understand this model. On July 2, 2019, a new Cloudflare firewall rule contained a regular expression whose critical part was .*(?:.*=.*). The backtracking engine executing it took superlinear time in the input length, exhausting the CPU of HTTP servers worldwide for 27 minutes, according to its public report. Three years earlier, in 2016, Stack Overflow was unavailable for 34 minutes because an expression removing trailing spaces encountered a post containing around 20,000 consecutive spaces. Neither expression required backtracking: both describe regular languages, which a finite automaton decides in linear time. This failure is called ReDoS, regular-expression denial of service. It is a common risk for systems accepting external text, including the attack surface of ML systems.

This lesson builds the theory: deterministic and nondeterministic automata and their equivalence, regular expressions and Kleene’s theorem, the limits of regular languages through the pumping lemma and Myhill-Nerode, minimization, and the Chomsky hierarchy. At the end, you will build a regular-expression engine from scratch that never backtracks and compare it with Python’s re module.

Strings and languages

An alphabet Σ\Sigma is a nonempty finite set of symbols. We will usually use Σ={0,1}\Sigma = \{0, 1\} or Σ={a,b}\Sigma = \{a, b\}. A string over Σ\Sigma is a finite sequence of symbols, and Σ∗\Sigma^* is the set of all such strings. With the notation of inductive definitions, Σ∗\Sigma^* is the smallest set containing the empty string ε\varepsilon and, whenever it contains ww, also containing wawa for every a∈Σa \in \Sigma. This definition underlies every induction on input length in the lesson.

We write ∣w∣\abs{w} for length, uvuv for concatenation, with εw=wε=w\varepsilon w = w\varepsilon = w, wkw^k for ww repeated kk times, and #a(w)\#_a(w) for the number of occurrences of symbol aa. A language is any subset L⊆Σ∗L \subseteq \Sigma^*. Besides the usual set operations, union, intersection, and complement L‾=Σ∗∖L\overline{L} = \Sigma^* \setminus L, languages have two further operations:

L1L2={uv:u∈L1, v∈L2},L∗=⋃k≥0Lk={w1w2⋯wk:k≥0, wi∈L},L_1 L_2 = \{uv : u \in L_1,\ v \in L_2\}, \qquad L^* = \bigcup_{k \ge 0} L^k = \{w_1 w_2 \cdots w_k : k \ge 0,\ w_i \in L\},

where L0={ε}L^0 = \{\varepsilon\}. The operation L∗L^* is the Kleene star, concatenation of any number of pieces of LL, including zero pieces.

One size distinction is worth keeping in mind. Σ∗\Sigma^* is countable, but the set of languages 2Σ∗2^{\Sigma^*} is not, by Cantor’s diagonal argument. Every computational model we study, including automata, grammars, and Turing machines, has a finite textual description, so there are only countably many of them. Almost all languages therefore cannot be recognized by any machine. We are interested in those that can.

Deterministic finite automata

Draw the automaton as a directed graph with a vertex for each state, an edge p→aqp \xrightarrow{a} q for each δ(p,a)=q\delta(p, a) = q, an incoming arrow marking q0q_0, and a double circle for accepting states. Reading ww follows the unique walk from q0q_0 labeled ww, and acceptance means ending in FF. It matters that δ\delta is a total function: exactly one edge leaves each state for each symbol. A missing edge in a diagram implicitly leads to a sink, a rejecting state that cannot be left.

Directly from the definition, δ^(q,uv)=δ^(δ^(q,u),v)\hat\delta(q, uv) = \hat\delta\big(\hat\delta(q, u), v\big) follows by induction on ∣v∣\abs{v}: the state after reading uu summarizes everything the automaton will use from uu. A useful way to design a DFA is to ask of each state what must be remembered about the prefix read so far, and check that this information can be updated one symbol at a time.

A proved example: binary multiples of 3

Read a binary number from its most significant bit and decide whether it is divisible by 3. Let val⁡(w)\operatorname{val}(w) be the number represented by ww, with val⁡(ε)=0\operatorname{val}(\varepsilon) = 0 and leading zeroes allowed. There is no need to remember the unbounded integer, only its remainder modulo 3. If a prefix has value vv and bit bb arrives, the new value is 2v+b2v + b and its remainder depends only on that of vv:

val⁡(wb)=2val⁡(w)+b⟹val⁡(wb) mod 3=(2 (val⁡(w) mod 3)+b) mod 3.\operatorname{val}(wb) = 2\operatorname{val}(w) + b \quad\Longrightarrow\quad \operatorname{val}(wb) \bmod 3 = (2\,(\operatorname{val}(w) \bmod 3) + b) \bmod 3.

The DFA has Q={0,1,2}Q = \{0, 1, 2\}, q0=0q_0 = 0, F={0}F = \{0\} and δ(r,b)=(2r+b) mod 3\delta(r, b) = (2r + b) \bmod 3.

Proof

Use induction on ∣w∣\abs{w}. If w=εw = \varepsilon, then δ^(0,ε)=0=val⁡(ε) mod 3\hat\delta(0, \varepsilon) = 0 = \operatorname{val}(\varepsilon) \bmod 3. If w=ubw = ub and the assertion holds for uu, then

δ^(0,ub)=δ(δ^(0,u),b)=(2(val⁡(u) mod 3)+b) mod 3=(2val⁡(u)+b) mod 3=val⁡(ub) mod 3,\hat\delta(0, ub) = \delta\big(\hat\delta(0, u), b\big) = \big(2(\operatorname{val}(u) \bmod 3) + b\big) \bmod 3 = (2\operatorname{val}(u) + b) \bmod 3 = \operatorname{val}(ub) \bmod 3,

because reduction modulo 3 is compatible with sums and products. Finally, w∈L(M)  ⟺  δ^(0,w)=0  ⟺  3∣val⁡(w)w \in L(M) \iff \hat\delta(0, w) = 0 \iff 3 \mid \operatorname{val}(w).

∎

The statement that the state is val⁡(prefijo) mod 3\operatorname{val}(\text{prefijo}) \bmod 3 is a loop invariant of the automaton simulator. To prove any DFA correct, write the prefix property represented by each state, check that q0q_0 satisfies it for ε\varepsilon, that every transition preserves it, and that FF are exactly the states whose property implies membership in the language.

InteractiveAutomaton designer
Remove transitions q0 → q00Remove transitions q0 → q11Remove transitions q1 → q20Remove transitions q1 → q01Remove transitions q2 → q31Remove transitions q2 → q00Remove transitions q3 → q30,1q0q1q2q3
1101
4 / 4 symbols
  • active state
  • transition just used
  • double circle: accepting; incoming arrow: initial
Type
Symbol for the next transition
Input string
Automaton typeComplete DFA
Active after reading «1101»{q1}
Number of active states1
Verdict on «1101»rejects
Shortest counterexample: «1101». Your automaton rejects it, but it belongs to L={w:w contains 101}L = \{w : w \text{ contains } 101\}.
The starting automaton should recognize strings containing 101, but has an error. The tool searches all combinations of its state with the target language's state and returns the shortest string on which they disagree. Step through it, find and fix the offending transition by asking what each state must remember, and repeat until the tool certifies equivalence. Next load the NFA for strings ending in 01: after 0101 two states are active at once. Finally, start from scratch and design a DFA for strings with as many occurrences of 01 as 10. How many states do you need?

The starting error is in δ(q1,1)=q0\delta(q_1, 1) = q_0. State q1q_1 means that the prefix ends in 1, but neither ends in 10 nor contains 101. If another 1 arrives, the prefix ends in 11, whose longest suffix that is also a prefix of 101 is still 1. The automaton should remain in q1q_1. With the wrong transition it forgets that 1 and rejects 1101. The tool does not try random strings. It searches breadth-first through reachable pairs of states, one from your automaton and one from the correct automaton, and stops at the first pair with different acceptance. Since there are finitely many pairs, finding none proves equivalence.

Operations and decision problems

Proof

Let Mi=(Qi,Σ,δi,qi,Fi)M_i = (Q_i, \Sigma, \delta_i, q_i, F_i) be DFAs with L(Mi)=LiL(M_i) = L_i. For complement, exchange accepting and rejecting states, (Q1,Σ,δ1,q1,Q1∖F1)(Q_1, \Sigma, \delta_1, q_1, Q_1 \setminus F_1). Since δ1\delta_1 is total, each string ends in exactly one state, which accepts in the new automaton if and only if it did not in M1M_1. For the other operations, the product automaton runs both at once, with states Q1×Q2Q_1 \times Q_2, initial state (q1,q2)(q_1, q_2) and δ((p,q),a)=(δ1(p,a),δ2(q,a))\delta\big((p, q), a\big) = \big(\delta_1(p, a), \delta_2(q, a)\big). Induction on ∣w∣\abs{w} gives δ^((q1,q2),w)=(δ^1(q1,w),δ^2(q2,w))\hat\delta\big((q_1, q_2), w\big) = \big(\hat\delta_1(q_1, w), \hat\delta_2(q_2, w)\big). Choosing F1×F2F_1 \times F_2 as the accepting set yields L1∩L2L_1 \cap L_2; (F1×Q2)∪(Q1×F2)(F_1 \times Q_2) \cup (Q_1 \times F_2) gives union, and F1×(Q2∖F2)F_1 \times (Q_2 \setminus F_2) difference.

∎

Viewing a DFA as a graph gives immediate algorithms for questions that have no general solution for more powerful models.

  • Emptiness. L(M)=∅L(M) = \varnothing if and only if no state in FF is reachable from q0q_0. This reachability problem is solved by breadth-first search in O(∣Q∣ ∣Σ∣)\bigO(\abs{Q}\,\abs{\Sigma}) time, and the search also returns the shortest accepted string.
  • Equivalence. L(M1)=L(M2)L(M_1) = L(M_2) if and only if the symmetric difference (L1∖L2)∪(L2∖L1)(L_1 \setminus L_2) \cup (L_2 \setminus L_1) is empty, an emptiness check on the product. If there is a disagreement, breadth-first search finds the shortest string, whose length is less than ∣Q1∣ ∣Q2∣\abs{Q_1}\,\abs{Q_2}. This is what the figure above does.
  • Finiteness. L(M)L(M) is infinite if and only if a cycle is reachable from q0q_0 and can reach FF.

Nondeterminism

In a DFA each symbol leads to exactly one state. A nondeterministic finite automaton relaxes this rule: a state may have several outgoing edges with the same symbol, none, or edges labeled ε\varepsilon that can be followed without reading input. It accepts if any path through the string ends in an accepting state.

The set Δ^({q0},w)\hat\Delta(\{q_0\}, w) contains exactly the states reached by walks of q0q_0 whose labels, after removing ε\varepsilon, form ww. This parallel reading is shown by the designer’s “ends in 01” example. After reading 0101, q0q_0 is active for the loop and q2q_2 for the now-confirmed hypothesis that the last two symbols are 01. The NFA carries all hypotheses at once.

Nondeterminism is a design tool. “Ends in 01” takes three states: stay in q0q_0 and at some point guess that the 0 being read is the penultimate symbol. ε\varepsilon transitions also make union straightforward: add a new initial state with two ε\varepsilon edges to the initial states of the two automata, as in the designer’s final example. Surprisingly, this adds no computational power.

The key is that δ^D(E({q0}),w)=Δ^({q0},w)\hat\delta_D\big(E(\{q_0\}), w\big) = \hat\Delta(\{q_0\}, w) for every ww. The DFA’s state is the NFA’s active-state set. You will prove this by induction on ∣w∣\abs{w} in the exercises. The idea that nondeterminism can be eliminated by remembering sets is the subset construction, the result for which Rabin and Scott received the 1976 Turing Award. In practice, instead of all 2∣Q∣2^{\abs{Q}} subsets, construct only those reachable from E({q0})E(\{q_0\}) by breadth-first search. Sometimes there are few reachable subsets; sometimes there are many.

InteractiveSubset construction and state explosion
0,110,10,1q0q1q2q3
step 8 / 8
DFA states discovered (each square is an NFA state; below are the last nn symbols represented)
…000
…001
…010
…011
…100
…101
…110
…111
DFA state (subset)on 0on 1
… 2 earlier rows
{q0,q2}{q0,q3}{q0,q1,q3}
{q0,q1,q2}{q0,q2,q3}{q0,q1,q2,q3}
{q0,q3}{q0}{q0,q1}
{q0,q1,q3}{q0,q2}{q0,q1,q2}
{q0,q2,q3}{q0,q3}{q0,q1,q3}
{q0,q1,q2,q3}{q0,q2,q3}{q0,q1,q2,q3}
States versus n (logarithmic scale)
  • NFA: n + 1
  • Minimal DFA: 2ⁿ
  • subset being processed
  • its successor on 0
  • its successor on 1
  • dashed ring: in both successors
  • tinted background: accepting DFA state
3
NFA states4
Subsets discovered8
Processed · pending8 · 0
Total when complete8 = 2³
Current step
{q0,q1,q2,q3}: on 0 → {q0,q2,q3}; on 1 → {q0,q1,q2,q3}
Each DFA state contains q0q_0 and every qiq_i for which the iith symbol from the end is 1. The DFA remembers the last 3 symbols, and cannot forget any of them.
Each step takes a pending subset in blue, computes the ε-closures of its successors under 0 in orange and 1 in teal, and adds the new subsets. Increase n for the NFA with n + 1 states recognizing strings whose nth symbol from the end is 1: it always has 2ⁿ reachable subsets. Read each node label: each DFA state records the last n symbols. Then switch to the NFA with ε transitions. How many of the 2⁶ possible subsets appear, and why is the result a product automaton?

The explosion is inevitable.

Proof

The NFA is the one in the figure: q0q_0 has a loop for 0 and 1, q0→1q1q_0 \xrightarrow{1} q_1 and qi→0,1qi+1q_i \xrightarrow{0, 1} q_{i+1} for 1≤i<n1 \le i < n, with F={qn}F = \{q_n\}. For the lower bound, let MM be a DFA with L(M)=LnL(M) = L_n and suppose two distinct strings x≠yx \neq y of length nn reach the same state δ^(q0,x)=δ^(q0,y)\hat\delta(q_0, x) = \hat\delta(q_0, y). Choose a position ii where they differ, with xi=1x_i = 1 and yi=0y_i = 0, swapping names if necessary, and let z=0i−1z = 0^{i-1}. String xzxz has length n+i−1n + i - 1, so its nn-th symbol from the end is at position ii and is xi=1x_i = 1. Therefore xz∈Lnxz \in L_n. Likewise, yz∉Lnyz \notin L_n. But δ^(q0,xz)=δ^(δ^(q0,x),z)=δ^(δ^(q0,y),z)=δ^(q0,yz)\hat\delta(q_0, xz) = \hat\delta\big(\hat\delta(q_0, x), z\big) = \hat\delta\big(\hat\delta(q_0, y), z\big) = \hat\delta(q_0, yz), and the DFA would accept both or neither. Thus the 2n2^n strings of length nn reach pairwise distinct states.

∎

This is a special case of an idea we will soon name: two prefixes separated by some suffix cannot share a state. In practice, an NFA with mm states can be simulated in two ways with opposite costs. Simulating its state set, as in the designer, costs O(m)\bigO(m) per symbol, counting each edge as an operation and assuming a bounded number of edges per state, for a total of O(m ∣w∣)\bigO(m\,\abs{w}) without preprocessing. Compiling the DFA in advance costs O(1)\bigO(1) per symbol, but compilation can require 2m2^m states. Real engines such as RE2 and Rust’s engine take a middle path: they construct DFA states lazily, only when visited by the input, and retain them in a bounded cache.

Regular expressions and Kleene’s theorem

The usual abbreviations are syntactic sugar: r+=rr∗r^+ = rr^*, r?=r∣εr? = r \mid \varepsilon, a character class [abc]=a∣b∣c[abc] = a \mid b \mid c, the dot .. for any symbol, and r{2,3}=rr∣rrrr\{2,3\} = rr \mid rrr. For example, (0∣1)∗1(0∣1)(0∣1)(0 \mid 1)^* 1 (0 \mid 1)(0 \mid 1) describes L3L_3, and (a∣b)∗abb(a \mid b)^* abb describes strings ending in abbabb.

The proof has two halves, both constructive algorithms.

From expression to automaton: Thompson’s construction. By structural induction on rr, construct an NFA with ε\varepsilon transitions satisfying three invariants: it has a single initial state with no incoming arcs, a single accepting state with no outgoing arcs, and at most two arcs leave each state. The cases are:

  • Symbol aa: two states, i→afi \xrightarrow{a} f. For ε\varepsilon, i→εfi \xrightarrow{\varepsilon} f; for ∅\varnothing, two states with no arcs.
  • Concatenation rsrs: an ε\varepsilon arc from the final state of N(r)N(r) to the initial state of N(s)N(s). The initial state is that of N(r)N(r) and the final state is that of N(s)N(s).
  • Union r∣sr \mid s: a new initial state with ε\varepsilon arcs to the initial states of N(r)N(r) and N(s)N(s), and a new final state with incoming ε\varepsilon arcs from both previous final states.
  • Star r∗r^*: a new initial state ii and final state ff, with ε\varepsilon arcs from ii to the initial state of N(r)N(r) and to ff (zero repetitions), and from the final state of N(r)N(r) back to the initial state of N(r)N(r) and to ff (another repetition or exit).

Each case preserves the invariants and adds at most two states, so the NFA for rr has at most 2∣r∣2\abs{r} states. Here ∣r∣\abs{r} counts the symbols and the operators ∣\mid and ∗^* (Thompson, 1968). These invariants matter. A seemingly cheaper star construction uses no new states, with an ε\varepsilon arc from the initial state of N(r)N(r) to its final state (to skip rr) and another from final to initial (to repeat). It seems correct but is not: if the initial state of N(r)N(r) has incoming arcs, the skip becomes available midway through a path. With that recipe, a∗a^* works, and so does a∗ba^*b, but (a∗b)∗(a^*b)^* accepts aa: it reads aa, the loop in a∗a^* returns to the initial state, and the skip goes from there to the end without reading bb. The new initial state ii has no incoming arcs, preventing the skip after any input has been read.

From automaton to expression. Number the states of a DFA 1,…,m1, \dots, m and write Rij(k)R_{ij}^{(k)} for a regular expression describing strings that go from ii to jj with every intermediate state in {1,…,k}\{1, \dots, k\}. For k=0k = 0 there are only direct arcs (and ε\varepsilon if i=ji = j), giving a finite union of symbols. A path allowed to use state kk either does not use it, or goes from ii to kk, loops from kk to kk, and exits from kk to jj:

Rij(k)=Rij(k−1)  ∣  Rik(k−1)(Rkk(k−1))∗Rkj(k−1).R_{ij}^{(k)} = R_{ij}^{(k-1)} \;\big|\; R_{ik}^{(k-1)}\big(R_{kk}^{(k-1)}\big)^* R_{kj}^{(k-1)}.

The language is the union of the R1j(m)R_{1j}^{(m)} with j∈Fj \in F. This is the same recurrence as Floyd–Warshall for transitive closure, over the semiring of languages. The resulting expression can be exponential in mm, and in general this cannot be avoided.

Combining the three conversions, regular expressions, NFAs and DFAs are three ways to describe the same class of languages. Each is suited to a purpose: expressions for writing, NFAs for construction (union, concatenation and star are straightforward), and DFAs for execution and decision questions (complement, equivalence and minimization). For example, closure under complement is immediate for DFAs and far from obvious for expressions: what expression describes strings that do not contain 101?

What a finite automaton cannot do

A DFA with pp states cannot count beyond pp. If it reads more than pp symbols, the pigeonhole principle forces it to revisit a state. The input read between those two visits forms a loop that can be repeated any number of times without the automaton noticing.

This is the pumping lemma.

Proof

Let MM be a DFA for LL, and let p=∣Q∣p = \abs{Q}. Take s=s1⋯sn∈Ls = s_1 \cdots s_n \in L with n≥pn \ge p and let r0=q0r_0 = q_0 and rt=δ^(q0,s1⋯st)r_t = \hat\delta(q_0, s_1 \cdots s_t) be the states it visits. Among r0,r1,…,rpr_0, r_1, \dots, r_p there are p+1p + 1 states and only pp distinct ones, so rj=rkr_j = r_k for some 0≤j<k≤p0 \le j < k \le p. Take x=s1⋯sjx = s_1 \cdots s_j, y=sj+1⋯sky = s_{j+1} \cdots s_k and z=sk+1⋯snz = s_{k+1} \cdots s_n. Then ∣y∣=k−j≥1\abs{y} = k - j \ge 1 and ∣xy∣=k≤p\abs{xy} = k \le p. Since δ^(rj,y)=rk=rj\hat\delta(r_j, y) = r_k = r_j, induction on ii gives δ^(rj,yi)=rj\hat\delta(r_j, y^i) = r_j, and hence δ^(q0,xyiz)=δ^(rj,z)=δ^(rk,z)=rn∈F\hat\delta(q_0, xy^iz) = \hat\delta(r_j, z) = \hat\delta(r_k, z) = r_n \in F.

∎

The lemma is applied by contraposition, as a game against an adversary: the adversary picks pp, you pick s∈Ls \in L with ∣s∣≥p\abs{s} \ge p, the adversary picks a partition xyzxyz satisfying 1 and 2, and you pick ii with xyiz∉Lxy^iz \notin L. If you win for every pp and every partition, LL is not regular.

The pumping lemma concerns one string at a time. The definitive result compares strings and gives an exact characterization.

Proof

(1 ⇒ 2) Let MM be a DFA for LL. If δ^(q0,x)=δ^(q0,y)\hat\delta(q_0, x) = \hat\delta(q_0, y), then for every zz we have δ^(q0,xz)=δ^(δ^(q0,x),z)=δ^(q0,yz)\hat\delta(q_0, xz) = \hat\delta\big(\hat\delta(q_0, x), z\big) = \hat\delta(q_0, yz), so xz∈L  ⟺  yz∈Lxz \in L \iff yz \in L and x≡Lyx \equiv_L y. Thus strings in different ≡L\equiv_L classes reach different states: the index of ≡L\equiv_L is at most ∣Q∣\abs{Q}.

(2 ⇒ 1) Construct MLM_L with one state per class: Q={[x]}Q = \{[x]\}, q0=[ε]q_0 = [\varepsilon], δ([x],a)=[xa]\delta([x], a) = [xa] and F={[x]:x∈L}F = \{[x] : x \in L\}. The transition is well defined: if x≡Lyx \equiv_L y, then for every zz, the suffix azaz gives xaz∈L  ⟺  yaz∈Lxaz \in L \iff yaz \in L, that is, xa≡Lyaxa \equiv_L ya. FF is well defined too: with z=εz = \varepsilon, x≡Lyx \equiv_L y implies x∈L  ⟺  y∈Lx \in L \iff y \in L. Induction on ∣w∣\abs{w} gives δ^([ε],w)=[w]\hat\delta([\varepsilon], w) = [w], and hence MLM_L accepts ww if and only if w∈Lw \in L.

(Minimal and unique) By the first part, every DFA for LL has at least as many states as there are classes, and MLM_L attains that bound. If MM has exactly that many states, all are reachable (otherwise removing unreachable states would give a smaller DFA), and the map δ^(q0,x)↦[x]\hat\delta(q_0, x) \mapsto [x] is well defined by the first part. It is surjective because each class [x][x] is the image of δ^(q0,x)\hat\delta(q_0, x). It maps finite sets of equal size, hence it is bijective. It also preserves the initial state, transitions and acceptance: MM is MLM_L with renamed states.

∎

This is the Myhill–Nerode theorem. To prove a language nonregular, exhibit infinitely many pairwise distinguishable strings. To prove a DFA minimal, exhibit as many pairwise distinguishable strings as it has states. The bound 2n2^n for LnL_n did exactly that. Unlike the pumping lemma, this criterion never fails: if a language is nonregular, those distinguishable strings exist.

Minimization

The theorem establishes existence and uniqueness of the minimum DFA. We still need to calculate it from a given DFA. Two states p,qp, q of a DFA are distinguishable if some zz satisfies δ^(p,z)∈F\hat\delta(p, z) \in F and δ^(q,z)∉F\hat\delta(q, z) \notin F, or the reverse, and equivalent (p≈qp \approx q) otherwise. If all states are reachable, p≈qp \approx q says exactly that the prefixes reaching pp and qq lie in the same ≡L\equiv_L class. Merging equivalent states therefore yields the minimum DFA. Distinguishable pairs are found in rounds, from shortest distinguishing suffix to longest.

Proof

By induction on rr, a pair is marked in round rr if and only if its shortest distinguishing suffix has length rr. For r=0r = 0 this is the definition: ε\varepsilon distinguishes pp from qq exactly when one lies in FF and the other does not. For r≥1r \ge 1, if the shortest suffix is azaz with ∣z∣=r−1\abs{z} = r - 1, then zz distinguishes δ(p,a)\delta(p, a) from δ(q,a)\delta(q, a) and no shorter suffix does (if a shorter z′z' distinguished them, az′az' would distinguish pp from qq with length less than rr). The induction hypothesis marks that successor pair in round r−1r - 1, so {p,q}\{p, q\} is marked in round rr and not earlier, again by induction. Conversely, if {p,q}\{p, q\} is marked in round rr by symbol aa, its successor pair has a distinguishing suffix zz shorter than rr and azaz distinguishes {p,q}\{p, q\}. There are finitely many pairs, so the rounds stop after at most (∣Q∣2)\binom{\abs{Q}}{2} markings.

∎
InteractiveTable of distinguishable states
0101010101010101ABCDEFGH
BCDEFGHABCDEFG
merge
Minimal DFA: one class per group of reachable equivalent states (same color above)
0101010101A,EB,HCFG
  • cell: distinguishing suffix (color: marking round)
  • suffix run from the row state
  • run from the column state
  • dashed ring: unreachable
Stepmerge
Marked pairs25 of 28
Unreachable from the start stateD
States in the minimal DFA5 (of 8)
The table has a cell for each pair of states. Play the rounds: round 0 separates accepting from rejecting states with suffix ε. Each subsequent round marks pairs that, under some symbol, reach an already marked pair. The suffix in a cell is that symbol followed by the suffix of the pair reached. Select a cell to see the two runs proving that its pair is distinguishable. At the end, unmarked pairs (≡) merge. In the eight-state example, notice D: it is unreachable and does not appear in the minimum DFA. In the remainders modulo 6 example, why is the minimum automaton the one modulo 3?

For the DFA of remainders modulo 6 accepting {0,3}\{0, 3\}, the pairs {r0,r3}\{r_0, r_3\}, {r1,r4}\{r_1, r_4\} and {r2,r5}\{r_2, r_5\} are never marked. rr and r+3r + 3 have the same remainder modulo 3, and since 3∣63 \mid 6, the future value’s remainder modulo 3 depends only on the current remainder modulo 3. The algorithm rediscovers the automaton from the earlier section.

Three observations about the algorithm. First, remove unreachable states beforehand. The table does not identify them as redundant (in the example D is equivalent to F and would merge with it), but they do not correspond to any prefix and should be removed. Second, the naive cost is O(∣Q∣2 ∣Σ∣)\bigO(\abs{Q}^2\,\abs{\Sigma}) per round for up to ∣Q∣\abs{Q} rounds; working backwards from newly marked pairs reduces the total to O(∣Q∣2 ∣Σ∣)\bigO(\abs{Q}^2\,\abs{\Sigma}), and Hopcroft’s partition-refinement algorithm (1971) reaches O(∣Σ∣ ∣Q∣log⁡∣Q∣)\bigO(\abs{\Sigma}\,\abs{Q} \log \abs{Q}). Third, because the minimum DFA is unique, minimization gives a canonical form. Two regular expressions describe the same language if and only if their minimum DFAs are equal up to names, which can be checked by traversing them in parallel.

Beyond regular languages: the Chomsky hierarchy

The language {0n1n:n≥0}\{0^n1^n : n \ge 0\} is not regular (you will prove this in two ways in the exercises), but has an obvious finite description: the grammar with rule S→0S1∣εS \to 0S1 \mid \varepsilon. A grammar has nonterminal symbols (here SS), terminals (0 and 1), an initial symbol and rewriting rules α→β\alpha \to \beta. Its language consists of the terminal strings obtained from the initial symbol by applying rules. Chomsky (1956) classified grammars by the form of their rules. Each class corresponds exactly to a kind of machine:

TypeRulesMachineExampleMembership
3: regularA→aBA \to aB, A→aA \to a, A→εA \to \varepsilonfinite automaton(ab)∗(ab)^*linear time
2: context-freeA→γA \to \gammapushdown automaton0n1n0^n1^n, balanced parentheses, JSONO(n3)\bigO(n^3) in general (CYK); linear for LL and LR subclasses
1: context-sensitiveαAβ→αγβ\alpha A \beta \to \alpha\gamma\beta, γ≠ε\gamma \ne \varepsilonlinear bounded automatonanbncna^nb^nc^ndecidable, PSPACE-complete in general
0: unrestrictedα→β\alpha \to \betaTuring machinethe halting problemsemidecidable

This is the Chomsky hierarchy, whose inclusions are strict. In a regular grammar, each rule generates one symbol and moves to a nonterminal playing the role of a state: A→aBA \to aB is the arc A→aBA \xrightarrow{a} B. A pushdown automaton is an NFA with an unbounded stack. The stack is precisely the memory missing for 0n1n0^n1^n: push one symbol for each 0 and pop one for each 1. Context-free grammars describe the syntax of nearly all programming languages and nested formats. Thus restricting decoding to JSON with a recursive schema needs a pushdown automaton rather than a finite automaton. A linear bounded automaton is a Turing machine restricted to the space occupied by its input. The Turing machine, unrestricted in memory or steps, is the subject of the next lesson: the Turing machine.

The table can be read in terms of memory. Regular languages need finite memory; context-free languages add a stack; context-sensitive languages use as much space as the input; and type 0 allows as much memory as needed. Each step buys expressive power at the cost of decision problems. For context-free grammars, deciding whether two generate the same language is already undecidable.

Real engines: backtracking and automata

The “regular expressions” in Perl, PCRE, Java, JavaScript, .NET and Python’s re module do not run as automata. They use a backtracking engine, a depth-first search that tries alternatives in order, tries quantifiers from more repetitions to fewer, and backtracks when a branch fails. It is easy to implement, supports precise capture semantics (“the first alternative that works”), and admits extensions no finite automaton can provide. Its cost depends on the number of ways to try matching a string, rather than the number of states.

With (a+)+b(a^+)^+b against ana^n, the engine must try every way to divide the nn occurrences of aa among repetitions of the outer quantifier before concluding that bb is missing. Those ways are the compositions of nn; there are 2n−12^{n-1} of them, because each of the n−1n - 1 gaps between letters either separates repetitions or does not. NFA simulation maintains a set of states and never backtracks. After any prefix aka^k with k≥1k \ge 1 the set is the same, and the cost is O(m)\bigO(m) per symbol.

InteractiveReDoS: backtracking and automata
Operations to decide whether the entire string matches (logarithmic scale)
  • backtracking (Python re, PCRE, Java, JavaScript)
  • NFA simulation (RE2, Go, Rust)
Backtracking stops at n = 18 after exceeding 2.0 · 10⁶ operations, which is why the red curve ends there.
Pattern
Unit
Ending
Matching mode
16
Input«a»¹⁶ + «!»
Backtracking: operations5.2 · 10⁵
Automaton: operations204
Match? (backtracking / automaton)no / no
Backtracking growth≈ 2.00ⁿ
Automaton growthlinear
Thompson NFA states9
Vulnerable: each additional a multiplies backtracking work by 2.00. Extrapolating to n=50n = 50 gives about 9.0 · 10¹⁵ operations: 2.9 years at 10810^8 operations per second. For n=30n = 30, the automaton solves it in 386 operations.
Two engines written from scratch run the same pattern on a unit repeated n times followed by an ending. One backtracks with Python re semantics, and the other simulates Thompson's NFA. The plot counts operations so it is reproducible; time is proportional. With (a+)+b the red curve is a line on a logarithmic scale with slope log 2, showing exponential growth. Compare (a|aa)*b, whose ratio between consecutive steps approaches the golden ratio; a*a*a*b, which is polynomial; the atomic group; and the same (a+)+b with an input that matches. Enter your own patterns: which ones grow explosively? Also try a backreference: the automaton refuses it for good reason.

The common property of dangerous patterns is ambiguity: the NFA has many different paths reading the same string. In (a+)+(a^+)^+ there are 2n−12^{n-1}; in (a∣aa)∗(a \mid aa)^* there are as many as ways to write nn as an ordered sum of ones and twos, namely the Fibonacci number Fn+1F_{n+1}, which grows as φn\varphi^n with φ≈1.618\varphi \approx 1.618; in a∗a∗a∗a^*a^*a^* there are (n+22)\binom{n+2}{2}, a polynomial number. When the string fails to match, a backtracking engine traverses all these paths; the automaton traverses them in parallel and never needs to count them. That is why the danger arises when the match fails or takes a long time to reach a successful branch. On matching input, the first branch can succeed immediately.

There is a second, fundamental difference. Backreferences such as \1 require exactly repeating a captured group and take these engines beyond regular languages. The pattern (a*)b\1 describes {anban:n≥0}\{a^nba^n : n \ge 0\}, which is not regular: the strings ana^n are pairwise distinguishable because anbana^nba^n is in the language while ambana^mba^n is not when m≠nm \neq n. And (.+)\1 describes the “squares” wwww. Matching with backreferences is NP-complete (Aho, 1990). Engines that guarantee linear time, such as RE2, Go’s regexp package and Rust’s regex crate, simply do not support them. They follow Russ Cox (2007), who brought back Thompson’s construction (1968): a Thompson NFA and simulation by sets of states. RE2 and Rust add a cached lazy DFA; Go uses simulation alone. The worst-case cost is O(m n)\bigO(m\,n) for a pattern of size mm and text of size nn.

Detecting and mitigating ReDoS

For a system that accepts external text, defenses in decreasing order of robustness are:

  1. A linear-time engine for every pattern applied to untrusted inputs: RE2, a C++ library with bindings for Python and other languages; Go; Rust; or the RegexOptions.NonBacktracking option in .NET 7. This defense does not depend on reviewing each pattern.
  2. Unambiguous patterns. (a+)+b(a^+)^+b describes the same language as a+ba^+b. A frequent real case is (\w+\s?)*: when the space is missing, two consecutive repetitions of \w+ compete for the same letters, just as in (a+)+(a^+)^+. (\w+(\s\w+)*\s?)? describes exactly the same language without ambiguity because every repetition must start with a space. With 22 letters and a final sign, the first takes around half a second in re; the second handles 100,000 letters in milliseconds. As a rule, a quantifier applied to something already containing a quantifier, or a star over alternatives that can read the same string, deserves scrutiny.
  3. Cut off backtracking where the language remains unchanged. Since Python 3.11, re supports atomic groups (?>...) and possessive quantifiers (a++, a*+), which do not reopen a closed repetition. They are not a general guarantee and change pattern meaning if placed incorrectly.
  4. Resource limits on maximum input length (for a quadratic pattern, reducing 20,000 to 2,000 characters divides runtime by 100), maximum time per operation (the third-party regex module supports a timeout parameter), and isolation of the evaluating process.
  5. Detection using static analyzers that search for ambiguity in the pattern’s NFA, and growth tests like those in the figure, with increasing input lengths that force failure, measuring CPU as well as results. This is what the Cloudflare case lacked.

Implementation from scratch

Start with a DFA represented as a dictionary, exhaustively check the invariant for multiples of 3, and construct the product automaton.

[ ]A DFA, its invariant and the productBrowser
from itertools import product

def dfa_accepts(dfa, w):
    q = dfa["start"]
    for c in w:
        q = dfa["delta"][q][c]
    return q in dfa["accept"]

mod3 = {
    "start": 0,
    "accept": {0},
    "delta": {r: {"0": (2 * r) % 3, "1": (2 * r + 1) % 3} for r in range(3)},
}

def val(w):
    return int(w, 2) if w else 0

def strings(max_len, alphabet="01"):
    for L in range(max_len + 1):
        for t in product(alphabet, repeat=L):
            yield "".join(t)

n_checked = 0
for w in strings(12):
    q = mod3["start"]
    for i, c in enumerate(w):              # invariante: q == val(w[:i]) % 3 antes de leer w[i]
        assert q == val(w[:i]) % 3
        q = mod3["delta"][q][c]
    assert (q in mod3["accept"]) == (val(w) % 3 == 0)
    n_checked += 1
print(f"{n_checked} cadenas de longitud <= 12: el invariante y la aceptación se cumplen")

def product_dfa(A, B, op):
    """Autómata producto: estado (p, q); acepta según op(p en F_A, q en F_B)."""
    start = (A["start"], B["start"])
    delta, accept, todo, seen = {}, set(), [start], {start}
    while todo:
        p, q = s = todo.pop()
        if op(p in A["accept"], q in B["accept"]):
            accept.add(s)
        delta[s] = {}
        for c in "01":
            t = (A["delta"][p][c], B["delta"][q][c])
            delta[s][c] = t
            if t not in seen:
                seen.add(t)
                todo.append(t)
    return {"start": start, "accept": accept, "delta": delta}

par_unos = {"start": 0, "accept": {0}, "delta": {0: {"0": 0, "1": 1}, 1: {"0": 1, "1": 0}}}
ambos = product_dfa(mod3, par_unos, lambda a, b: a and b)
print("estados del producto:", len(ambos["delta"]))
assert all(dfa_accepts(ambos, w) == (val(w) % 3 == 0 and w.count("1") % 2 == 0) for w in strings(10))
print("intersección correcta en todas las cadenas de longitud <= 10")

Next, implement a general NFA with ε\varepsilon transitions stored under the symbol "", and subset construction limited to reachable states. The family LnL_n confirms the exponential growth.

[ ]Subset construction and its blow-upBrowser
import time

def closure(nfa, S):
    """ε-clausura: todo lo alcanzable desde S por transiciones ε (símbolo '')."""
    S, todo = set(S), list(S)
    while todo:
        q = todo.pop()
        for t in nfa["delta"].get((q, ""), ()):
            if t not in S:
                S.add(t)
                todo.append(t)
    return frozenset(S)

def subset_construction(nfa, alphabet="01"):
    start = closure(nfa, {nfa["start"]})
    delta, todo = {}, [start]
    while todo:
        S = todo.pop()
        if S in delta:
            continue
        delta[S] = {}
        for c in alphabet:
            T = closure(nfa, {t for q in S for t in nfa["delta"].get((q, c), ())})
            delta[S][c] = T
            if T not in delta:
                todo.append(T)
    accept = {S for S in delta if S & nfa["accept"]}
    return {"start": start, "accept": accept, "delta": delta}

def nth_from_end(n):
    d = {(0, "0"): {0}, (0, "1"): {0, 1}}
    for i in range(1, n):
        d[(i, "0")] = d[(i, "1")] = {i + 1}
    return {"start": 0, "accept": {n}, "delta": d}

for n in range(1, 13):
    D = subset_construction(nth_from_end(n))
    print(f"n = {n:2d}: NFA con {n + 1:2d} estados -> DFA con {len(D['delta']):5d} estados")

D = subset_construction(nth_from_end(4))
assert all(dfa_accepts(D, w) == (len(w) >= 4 and w[-4] == "1") for w in strings(9))
print("el DFA de n = 4 es correcto en todas las cadenas de longitud <= 9")

With n=12n = 12, an NFA with 13 states gives a DFA with 4,096. Next are regular expressions. The parser is recursive descent, with one function per precedence level, and produces a tree of tuples.

[ ]Regular-expression parserBrowser
class Parser:
    """alt := cat ('|' cat)*     cat := rep*     rep := atom ('*' | '+' | '?')*
       atom := '(' alt ')' | '.' | barra invertida + símbolo | símbolo"""

    def __init__(self, src):
        self.s, self.i = src, 0

    def peek(self):
        return self.s[self.i] if self.i < len(self.s) else None

    def take(self):
        c = self.peek()
        self.i += 1
        return c

    def parse(self):
        ast = self.alt()
        if self.peek() is not None:
            raise SyntaxError(f"sobra {self.peek()!r} en la posición {self.i}")
        return ast

    def alt(self):
        node = self.cat()
        while self.peek() == "|":
            self.take()
            node = ("alt", node, self.cat())
        return node

    def cat(self):
        node = ("eps",)
        while self.peek() not in (None, "|", ")"):
            r = self.rep()
            node = r if node == ("eps",) else ("cat", node, r)
        return node

    def rep(self):
        node = self.atom()
        while self.peek() in ("*", "+", "?"):
            node = ({"*": "star", "+": "plus", "?": "opt"}[self.take()], node)
        return node

    def atom(self):
        c = self.take()
        if c == "(":
            node = self.alt()
            if self.take() != ")":
                raise SyntaxError("falta ')'")
            return node
        if c == ".":
            return ("any",)
        if c == chr(92):                       # la barra invertida escapa el símbolo siguiente
            return ("char", self.take())
        if c in (None, ")", "*", "+", "?", "|"):
            raise SyntaxError(f"símbolo inesperado {c!r} en la posición {self.i - 1}")
        return ("char", c)

def parse(src):
    return Parser(src).parse()

for r in ["ab|c", "(a|b)*abb", "a(b|)c?", "(a+)+b"]:
    print(f"{r:10s} ->", parse(r))

Thompson’s construction follows the four cases above. Each state has type char (one arc labeled by a symbol), any (one arc for any symbol), split (up to two ε\varepsilon arcs), or match (the end). A fragment’s final state is an split whose successors are filled in during composition. The code additionally adds an explicit match state at the end, one more than in the theoretical count. For star, it uses Russ Cox’s variant with the same two new states: the body’s end returns to entrance ii, which chooses another repetition or exit. This is correct because ii is reached only at the start or after a complete repetition, precisely the times when exit is allowed.

[ ]Thompson, ε-closure and set simulationBrowser
import re, random

class NFA:
    """kind[q] en {'char', 'any', 'split', 'match'}; out1 y out2 son los sucesores."""

    def __init__(self):
        self.kind, self.sym, self.out1, self.out2 = [], [], [], []

    def new(self, kind, sym=None, out1=None, out2=None):
        self.kind.append(kind); self.sym.append(sym); self.out1.append(out1); self.out2.append(out2)
        return len(self.kind) - 1

def thompson(ast):
    """Devuelve (nfa, inicio). Cada fragmento tiene un estado de entrada y un estado final (un 'split'
    sin sucesores) que se enlaza después: cada operador añade como mucho 2 estados."""
    nfa = NFA()

    def build(node):
        op = node[0]
        if op == "eps":
            e = nfa.new("split")
            return e, e
        if op in ("char", "any"):
            end = nfa.new("split")
            s = nfa.new(op, node[1] if op == "char" else None, end)
            return s, end
        if op == "cat":
            s1, e1 = build(node[1])
            s2, e2 = build(node[2])
            nfa.out1[e1] = s2                       # arco ε del final del primero al inicio del segundo
            return s1, e2
        if op == "alt":
            s1, e1 = build(node[1])
            s2, e2 = build(node[2])
            end = nfa.new("split")
            nfa.out1[e1] = nfa.out1[e2] = end
            return nfa.new("split", None, s1, s2), end
        s1, e1 = build(node[1])
        end = nfa.new("split")
        if op == "star":                            # entrada: al cuerpo o fuera; el cuerpo vuelve a la entrada
            s = nfa.new("split", None, s1, end)
            nfa.out1[e1] = s
            return s, end
        if op == "plus":                            # el cuerpo al menos una vez
            loop = nfa.new("split", None, s1, end)
            nfa.out1[e1] = loop
            return s1, end
        if op == "opt":
            nfa.out1[e1] = end
            return nfa.new("split", None, s1, end), end
        raise ValueError(op)

    s, e = build(ast)
    nfa.out1[e] = nfa.new("match")
    return nfa, s

def eps_closure(nfa, states):
    seen, todo = set(), list(states)
    while todo:
        q = todo.pop()
        if q is None or q in seen:
            continue
        seen.add(q)
        if nfa.kind[q] == "split":
            todo.append(nfa.out1[q])
            todo.append(nfa.out2[q])
    return frozenset(seen)

def step(nfa, S, c):
    return eps_closure(nfa, [nfa.out1[q] for q in S
                             if (nfa.kind[q] == "char" and nfa.sym[q] == c) or nfa.kind[q] == "any"])

class Regex:
    def __init__(self, pattern):
        self.pattern = pattern
        self.nfa, self.start = thompson(parse(pattern))
        self.match_state = len(self.nfa.kind) - 1

    def fullmatch(self, s):
        S = eps_closure(self.nfa, [self.start])
        for c in s:
            S = step(self.nfa, S, c)
            if not S:
                return False
        return self.match_state in S

rnd = random.Random(0)
patrones = ["(a|b)*abb", "a(b|c)*d?", "(ab|a)*c", "(a+)+b", "((a|b)(a|b))*", "a?b+.c*", "(a|)(b|c)*"]
for p in patrones:
    R, ref = Regex(p), re.compile(p)
    for _ in range(2000):
        s = "".join(rnd.choice("abcd") for _ in range(rnd.randrange(9)))
        assert R.fullmatch(s) == bool(ref.fullmatch(s)), (p, s)
    print(f"{p:14s} {len(R.nfa.kind):3d} estados   2000 cadenas al azar: mismo resultado que re")

The seven patterns agree with re.fullmatch on all 14,000 strings. (a∣b)∗abb(a \mid b)^*abb has 15 states: the 14 from the count (2⋅52 \cdot 5 symbols, two for union and two for star), plus match. Next is the lazy DFA: the same simulation, but each appearing set of states gets a number and each calculated transition is cached. After a few symbols, every step is a dictionary lookup.

[ ]Lazy DFA with cacheBrowser
import time

class LazyDFA(Regex):
    """Construcción de subconjuntos bajo demanda: cada conjunto de estados del NFA se guarda una vez
    con un número, y cada transición se calcula la primera vez que hace falta."""

    def __init__(self, pattern):
        super().__init__(pattern)
        self.ids, self.sets, self.trans = {}, [], {}
        self.q0 = self._id(eps_closure(self.nfa, [self.start]))

    def _id(self, S):
        if S not in self.ids:
            self.ids[S] = len(self.sets)
            self.sets.append(S)
        return self.ids[S]

    def fullmatch(self, s):
        q = self.q0
        for c in s:
            nxt = self.trans.get((q, c))
            if nxt is None:
                nxt = self.trans[(q, c)] = self._id(step(self.nfa, self.sets[q], c))
            q = nxt
        return self.match_state in self.sets[q]

rnd = random.Random(1)
texto = "".join(rnd.choice("ab") for _ in range(30000)) + "abb"
for Motor in (Regex, LazyDFA):
    m = Motor("(a|b)*abb")
    t = time.perf_counter()
    r = m.fullmatch(texto)
    print(f"{Motor.__name__:8s} resultado = {r}   {time.perf_counter() - t:.3f} s")
print("estados del DFA construidos:", len(m.sets), "  transiciones en caché:", len(m.trans))

For 30,003 characters, the lazy DFA builds five states and nine transitions, and runs much faster than set simulation, which recomputes closure at every symbol. To minimize it, complete the lazy DFA by traversing all reachable states and apply table filling.

[ ]Complete and minimizeBrowser
def full_dfa(motor, alphabet):
    """Completa el DFA perezoso recorriendo todo lo alcanzable."""
    todo, seen = [motor.q0], {motor.q0}
    while todo:
        q = todo.pop()
        for c in alphabet:
            if (q, c) not in motor.trans:
                motor.trans[(q, c)] = motor._id(step(motor.nfa, motor.sets[q], c))
            t = motor.trans[(q, c)]
            if t not in seen:
                seen.add(t)
                todo.append(t)
    Q = sorted(seen)
    delta = {(q, c): motor.trans[(q, c)] for q in Q for c in alphabet}
    return Q, delta, {q for q in Q if motor.match_state in motor.sets[q]}

def minimize(Q, delta, F, alphabet):
    """Llenado de tabla hasta el punto fijo; devuelve el número de clases y el representante de cada estado."""
    marked = {(p, q) for p in Q for q in Q if (p in F) != (q in F)}
    changed = True
    while changed:
        changed = False
        for p in Q:
            for q in Q:
                if p < q and (p, q) not in marked:
                    if any((delta[(p, c)], delta[(q, c)]) in marked for c in alphabet):
                        marked |= {(p, q), (q, p)}
                        changed = True
    clase = {q: next(p for p in Q if p == q or (p, q) not in marked) for q in Q}
    return len(set(clase.values())), clase

casos = [("(a|b)*abb", "ab"), ("(0|1)*1(0|1)(0|1)", "01"), ("(a|b)*a(a|b)(a|b)(a|b)(a|b)(a|b)", "ab"),
         ("(a|b)*", "ab"), ("(a*b*)*", "ab"), ("a*(ba*ba*)*", "ab")]
for p, alfabeto in casos:
    Q, delta, F = full_dfa(LazyDFA(p), alfabeto)
    k, _ = minimize(Q, delta, F, alfabeto)
    print(f"{p:34s} DFA por subconjuntos: {len(Q):3d} estados   mínimo: {k}")

The minimum DFAs for L3L_3 and L6L_6 have 8 and 64 states, as the 2n2^n bound predicts. (a∣b)∗(a \mid b)^* and (a∗b∗)∗(a^*b^*)^* have the same one-state minimum DFA: they are two expressions for the same language, as minimization proves. And a∗(ba∗ba∗)∗a^*(ba^*ba^*)^*, “an even number of bb,” reduces to two states.

Finally, the ReDoS experiment uses real clocks: re.fullmatch versus our engine in (a+)+b(a^+)^+b on ana^n, stopping as soon as re takes more than a quarter of a second.

[ ]Python re versus the non-backtracking engineBrowser
filas = []
for n in range(10, 31, 2):
    s = "a" * n
    t = time.perf_counter(); r1 = re.fullmatch("(a+)+b", s); t_re = time.perf_counter() - t
    t = time.perf_counter(); r2 = LazyDFA("(a+)+b").fullmatch(s); t_propio = time.perf_counter() - t
    assert bool(r1) == r2
    filas.append((n, t_re, t_propio))
    if t_re > 0.25:
        break
for n, a, b in filas:
    print(f"n = {n:2d}   re: {a * 1e3:9.2f} ms   motor propio (incluida la compilación): {b * 1e3:6.2f} ms")
print(f"cociente de tiempos de re entre n = {filas[-2][0]} y n = {filas[-1][0]}: {filas[-1][1] / filas[-2][1]:.1f}")

for p in ["(?>a+)+b", "(a++)+b", "a+b"]:
    t = time.perf_counter(); re.fullmatch(p, "a" * 100000)
    print(f"{p:9s} con n = 100000: {(time.perf_counter() - t) * 1e3:.2f} ms")

re takes roughly four times as long for each additional pair of letters, as 2n2^n predicts, until the loop stops. Our engine’s time stays unchanged, dominated by compiling a nine-state NFA. The atomic group, possessive quantifier and non-nested rewrite a+ba^+b handle n=100 000n = 100\,000 in milliseconds.

The professional version

ToolModelGuaranteeWhen
re (Python), PCRE, Java, JavaScriptbacktrackingnone: exponential worst casecontrolled patterns on trusted input; when backreferences are needed
RE2 (pip install google-re2), Go regexp, Rust regexThompson NFA (RE2 and Rust add a lazy DFA)O(m n)\bigO(m\,n)any untrusted input
.NET with RegexOptions.NonBacktrackingautomatonlinearthe same, in .NET
regex (third-party Python)backtrackingnone, but supports timeoutwhen its extensions are needed
lex, flex, re2ccompiled DFAlinear, without cachelexical analyzers

In Python, compile patterns once with re.compile, and distinguish fullmatch (the entire string, i.e. membership in the language), match (a prefix), and search (any substring). Python’s RE2 interface resembles re, so for patterns using only regular constructs the change takes one line:

import re2  # pip install google-re2

patron = re2.compile(r"(a+)+b")
patron.fullmatch("a" * 100_000)   # tiempo lineal: devuelve None sin explorar ramas

If a pattern uses a backreference or assertion unsupported by RE2, compilation fails. A library promising linear time must make this distinction explicit.

Common mistakes

Exercises

NumericMultiples of 3
How many states does the minimal complete DFA recognizing binary numbers divisible by 3 have? Read the most significant bit first, allow leading zeros, and take val⁡(ε)=0\operatorname{val}(\varepsilon) = 0.
NumericCounting Thompson states
Using the Thompson rules in this lesson (2 states per symbol, 2 more per union and per star, and no new state for concatenation, which adds only an ε edge), how many states does the NFA for (a∣b)∗abb(a \mid b)^*abb have?
NumericAn exact bound
How many states does the minimal complete DFA for L5L_5, the binary strings whose fifth symbol from the end is 1, have?
QuizRegular or not?
Which of these languages over {0,1}\{0, 1\} are regular?

More than one answer may be correct.

QuizWhat the pumping lemma says
A language LL satisfies the pumping-lemma conclusion with p=3p = 3: every string in LL of length at least 3 can be split as in the lemma and pumped while remaining in LL. What follows?
QuizWhich patterns explode?
With Python 3.11 or later module re, which of these patterns take exponential time in nn in the following full-match test? re.fullmatch(patron, 'a' * n + '!')

More than one answer may be correct.

Proof0ⁿ1ⁿ is not regular: pumping lemma
Prove: The language L={0n1n:n≥0}L = \{0^n1^n : n \ge 0\} is not regular.
0
Suppose for contradiction that LL is regular and let pp be the pumping length given by the lemma.

Step 1 of 4. Which string do you choose?

Proof0ⁿ1ⁿ is not regular: Myhill-Nerode
Prove: The language L={0n1n:n≥0}L = \{0^n1^n : n \ge 0\} has infinitely many ≡L\equiv_L classes and is therefore not regular.
0
By the Myhill-Nerode theorem, it suffices to find infinitely many pairwise distinguishable strings.

Step 1 of 3. Which family of strings do you propose?

ProofCorrectness of subset construction
Prove: Let N=(Q,Σ,Δ,q0,F)N = (Q, \Sigma, \Delta, q_0, F) be an NFA with ε transitions and let DD be its subset DFA. For every w∈Σ∗w \in \Sigma^*, δ^D(E({q0}),w)=Δ^({q0},w)\hat\delta_D(E(\{q_0\}), w) = \hat\Delta(\{q_0\}, w), and hence L(D)=L(N)L(D) = L(N).
0
Proceed by induction on ∣w∣\abs{w}.

Step 1 of 3. What is the base case?

CodeSimulate an NFA with ε closure
Implement nfa_accepts(nfa, s). The NFA is a dictionary with 'start' (a state), 'accept' (a set) and 'delta', which maps each (estado, símbolo) pair to a set of states. The symbol '' denotes ε transitions. Missing pairs have no transition. Return True if the NFA accepts string s. Take care with the empty string and ε-transition cycles.
def nfa_accepts(nfa, s):
  """True si el NFA acepta s."""
  current = {nfa["start"]}
  for c in s:
      nxt = set()
      for q in current:
          nxt |= nfa["delta"].get((q, c), set())
      current = nxt
  return bool(current & nfa["accept"])
Shift+Enter to run
CodeConstructing and minimizing multiples of 5
Implement dfa_mod5(), returning the DFA in the lesson's format ('start', 'accept' and 'delta' with delta[q][c] for c in '01') for binary strings ww with val⁡(w)\operatorname{val}(w) divisible by 5 (with val⁡(ε)=0\operatorname{val}(\varepsilon) = 0), and minimize(dfa), returning an equivalent DFA with the minimum number of states using table filling after removing unreachable states. Tests compare every string up to length 16 with integer arithmetic and verify that minimize reduces a redundant DFA.
def dfa_mod5():
  """DFA de los múltiplos de 5 en binario (estado = resto)."""
  return {"start": 0, "accept": {0},
          "delta": {r: {"0": (2 * r) % 3, "1": (2 * r + 1) % 3} for r in range(3)}}

def minimize(dfa):
  """Devuelve un DFA mínimo equivalente."""
  return dfa
Shift+Enter to run

Summary

Key idea
A finite automaton reads once and remembers a bounded amount of information. The languages it recognizes, the regular languages, are exactly those decidable by distinguishing finitely many classes of prefixes. This makes all the decision problems in this lesson exactly solvable.
  • Design a DFA by deciding what each state remembers about the prefix, then prove it correct by induction over the input using that invariant. The product gives intersection and union, swapping accepting states gives complement, and reachability gives emptiness and equivalence.
  • An NFA follows all hypotheses at once. The subset construction converts it to a DFA whose state is the active-state set and may inevitably require 2n2^n states, as for LnL_n.
  • Regular expressions, NFAs, and DFAs describe the same class of languages by Kleene’s theorem. Thompson’s construction yields a linear-size NFA, and the recurrence Rij(k)R_{ij}^{(k)} yields a regular expression.
  • The pumping lemma, derived from the pigeonhole principle on states, can disprove regularity. Myhill-Nerode gives a characterization: LL is regular if and only if ≡L\equiv_L has finitely many classes. Their number is the size of the unique minimal DFA, computable by table filling.
  • Above regular languages are context-free grammars with a stack, context-sensitive grammars, and Turing machines. Each level adds memory and loses decidable questions.
  • Backtracking engines take time proportional to the number of possible matches, exponential for ambiguous patterns. Automaton-based engines such as RE2, Go, and Rust guarantee O(m n)\bigO(m\,n) by forgoing backreferences. Use one when processing untrusted input.