Automata & Regular Languages
The simplest model of computation — alphabets, strings and languages, deterministic finite automata, nondeterministic automata and subset construction, regular expressions and their equivalence with automata, closure properties, the pumping lemma, minimisation, and how regex engines work (and blow up).
Automata theory studies abstract machines and the problems they can solve. The simplest — finite automata — have a fixed, finite memory. They are the theory behind regular expressions, lexers (Lexical analysis), protocol state machines, input validation and UI states.
Alphabets, strings and languages
| Term | Meaning | Example |
|---|---|---|
| Alphabet Σ | A finite set of symbols | {0, 1}, ASCII |
| String | A finite sequence of symbols | 0110; ε is the empty string |
| Language | A set of strings (possibly infinite) | All binary strings with an even number of 1s |
"Solving a problem" can be phrased as deciding membership: is this string in the language? ("Is this a valid email?", "Is this number divisible by 3?", "Does this program halt?")
Deterministic finite automata (DFA)
A DFA has a finite set of states, a start state, a set of accepting states, and a transition function δ(state, symbol) → state. It reads the input one symbol at a time and accepts if it ends in an accepting state.
Example: binary strings with an even number of 1s.
EVEN (green) is both the start state and the accepting state. Each state also loops to itself on 0. In code, a DFA is a table lookup per character — O(n) time, O(1) memory:
def divisible_by_3(binary: str) -> bool:
# states: remainder mod 3 of the number read so far
state = 0
for bit in binary:
state = (state * 2 + int(bit)) % 3 # δ(r, b) = (2r + b) mod 3
return state == 0
print(divisible_by_3("110")) # 6 → True
print(divisible_by_3("111")) # 7 → FalseA DFA's memory is just its current state — it cannot count without bound. That limitation defines what it can and can't do.
Nondeterministic finite automata (NFA)
An NFA may have several transitions on the same symbol, or ε-transitions that consume no input. It accepts if some sequence of choices leads to an accepting state — think of it as exploring all paths in parallel.
NFAs are often much smaller and easier to build. E.g. "strings whose third-from-last symbol is 1" needs only 4 NFA states (guess when the third-from-last symbol arrives) but 8 DFA states.
Subset construction
Every NFA can be converted to an equivalent DFA: each DFA state represents the set of NFA states the machine could be in. So NFAs are no more powerful than DFAs — but the DFA can have up to states for an n-state NFA.
Regular expressions
A regular expression describes a language using three operations on smaller expressions, plus base cases:
| Operation | Syntax | Language |
|---|---|---|
| Union | a|b | a or b |
| Concatenation | ab | a followed by b |
| Kleene star | a* | zero or more a's |
| Base cases | a, ε, ∅ | single symbol, empty string, empty language |
Everything else is shorthand: a+ = aa*, a? = a|ε, [a-z] = a union of letters, a{2,3} = aa|aaa.
Kleene's theorem
Regular expressions, NFAs and DFAs describe exactly the same class of languages — the regular languages:
- Regex → NFA: Thompson's construction builds small NFA fragments for each operator and glues them with ε-transitions.
- NFA → DFA: subset construction.
- DFA → regex: state elimination.
This is how lexer generators and fast regex engines work: compile the pattern to an automaton, then run it in linear time.
Closure properties
Regular languages are closed under union, concatenation, star, intersection, complement (swap accepting and non-accepting DFA states), difference and reversal. Intersection uses the product construction: run two DFAs in parallel with paired states. These closures make regular languages easy to combine and analyse — e.g. checking whether two regexes are equivalent is decidable.
What finite automata can't do
Regular languages can't count without bound. The classic non-regular language:
Intuition: a DFA with k states reading must revisit some state (pigeonhole — Combinatorics), so it can't remember exactly how many a's it saw.
The pumping lemma
If L is regular, there is a length p such that every string s ∈ L with can be split as s = xyz where , , and for all i ≥ 0 (the loop y can be "pumped").
To show is not regular: take . Any y within the first p symbols consists only of a's; pumping it changes the number of a's but not b's, giving a string not in L. Contradiction.
Other non-regular languages: balanced parentheses, palindromes, {ww}, valid arithmetic expressions, and HTML. That's why you can't correctly parse nested HTML or JSON with a (true) regular expression — you need a parser for a context-free grammar (Context-free grammars).
DFA minimisation
Every regular language has a unique minimal DFA (up to renaming states). Algorithms (Hopcroft's, O(n log n)) merge states that no input string can distinguish. The Myhill–Nerode theorem characterises regular languages exactly: L is regular iff its strings fall into finitely many "distinguishable" classes — the number of classes is the minimal DFA's size.
Real regex engines
Practical regex libraries take two approaches:
| Approach | Engines | Time | Features |
|---|---|---|---|
| Automata-based (Thompson NFA / lazy DFA) | RE2, Rust regex, Go regexp, grep, ripgrep | Guaranteed linear in input length | No backreferences or lookaround (they aren't regular) |
| Backtracking | PCRE, Perl, Python re, JavaScript, Java | Usually fast, exponential in the worst case | Backreferences, lookahead/lookbehind, possessive quantifiers |
Catastrophic backtracking (ReDoS)
A backtracking engine tries alternatives one by one. Nested quantifiers can make it explore exponentially many ways to fail:
import re, time
pattern = re.compile(r"^(a+)+$")
s = "a" * 28 + "!" # almost matches
t = time.time(); pattern.match(s); print(f"{time.time() - t:.1f}s") # seconds, doubling per extra 'a'Attackers exploit this with crafted input to freeze servers — ReDoS (it took down Stack Overflow in 2016 and Cloudflare's network in 2019). Defences: avoid nested quantifiers and overlapping alternations, set timeouts, limit input length, or use a linear-time engine like RE2 for untrusted input.
Where finite automata appear
- Lexers and tokenisers in every compiler and interpreter.
- Protocol and UI state machines: TCP's connection states (TCP), order lifecycles, checkout flows — explicit state machines prevent impossible transitions (State pattern).
- Text search: grep, ripgrep, Aho–Corasick multi-pattern matching, KMP's failure function (String algorithms).
- Input validation, network packet filters, hardware controllers (sequential circuits are finite automata — Sequential circuits), model checking.
- A language is a set of strings; recognising it means deciding membership.
- DFAs read input in one pass with finite memory (the current state): O(n) time, O(1) space.
- NFAs allow choices and ε-moves; subset construction converts them to DFAs (possibly exponentially larger).
- Kleene's theorem: regular expressions, NFAs and DFAs define the same languages — the regular languages.
- Regular languages are closed under union, intersection, complement, concatenation and star.
- They can't count without bound (aⁿbⁿ, balanced parentheses, HTML) — proved via the pumping lemma.
- Backtracking regex engines can blow up exponentially (ReDoS); automata-based engines guarantee linear time.