Optimising the lexer DFA
How to reduce time and memory cost of a lexer by turning regular expressions → NFA → DFA then applying state reduction, alphabet reduction and table compression, with exact algorithms and worked traces.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Optimising the lexer DFA reduces the memory and runtime cost of scanning source code. Engineers use these techniques in compilers, interpreters and tools (lex/Flex, custom scanners) so the scanner is fast, uses less memory and preserves the lexer semantics such as longest-match and rule priority.
Key ideas
(Definitions are bold and introduced before use.)
Alphabet (Σ): the finite set of input characters (for programming languages it is often the byte set). We may reduce Σ by grouping characters into character classes.
NFA (nondeterministic finite automaton): a 5-tuple (Q, Σ, Δ, q0, F) where Q is the set of states, Σ the alphabet, Δ ⊆ Q × (Σ ∪ {ε}) × Q the transition relation (ε for empty transition), q0 the start state and F the set of accepting states. An NFA accepts a string if there exists some path following transitions (including ε) from q0 to a state in F that spells that string.
DFA (deterministic finite automaton): a 5-tuple (Q, Σ, δ, q0, F) where δ: Q × Σ → Q is a total function (exactly one target per state+symbol). A DFA runs in time proportional to the input length and needs one state transition per input symbol.
Subset construction (NFA→DFA): builds DFA states that are sets of NFA states (use ε-closures). Start DFA state is ε-closure({q0}); for each DFA state S and symbol a, the target is ε-closure(move(S,a)). It is correct by construction: a DFA state S represents that the NFA could be in any state of S after reading the same input. Worst-case number of reachable DFA states is ≤ 2^{|Q_NFA|} (power-set).
Equivalent states: two DFA states p and q are equivalent if for every input string w they either both lead to acceptance or both to rejection. Formally, p ~ q iff for all w ∈ Σ*, δ*(p,w) ∈ F ⇔ δ*(q,w) ∈ F.
Myhill–Nerode theorem (exact statement you should remember): For a language L ⊆ Σ*, the equivalence relation ≡_L defined by x ≡_L y iff for all z ∈ Σ* (xz ∈ L ⇔ yz ∈ L) has a finite number of equivalence classes iff L is regular. The minimum DFA for L has exactly one state per equivalence class. Assumption: Σ is finite. Use this theorem as the correctness basis for DFA minimisation.
DFA minimisation: the process of merging equivalent states to obtain the unique (up to renaming) smallest DFA that recognises the same language. Standard algorithms: partition-refinement (Hopcroft) and the slower table-filling (a.k.a. partition by distinguishability). In lexer DFAs with multiple accepting actions/priorities, initialise the partition by splitting accepting states by their action/priority (not a single block F) to preserve rule priority and token kinds.
Hopcroft's algorithm (high-level): start with partition P = {F, Q\F}. Maintain a worklist W of splitters. Repeatedly take a splitter A from W and, for each input symbol a, compute Pre_a(A) = {q | δ(q,a) ∈ A}. For each partition Y in P that intersects Pre_a(A) non-trivially, split Y into Y1 = Y ∩ Pre_a(A) and Y2 = Y \ Pre_a(A). Replace Y in P by Y1 and Y2; add the smaller of Y1 or Y2 to W. Continue until W empty. The resulting P is the set of equivalence classes. Hopcroft refines partitions efficiently.
Correctness assumptions: DFA is complete (δ is total) or equivalently add a dead sink state first. The algorithm terminates because each split increases the number of partition blocks, bounded by |Q|. The partition at the end is Myhill–Nerode classes.
Dead/unreachable state elimination: remove states unreachable from the start. For states that cannot reach any accepting state, collapse them into a single dead sink state (use reverse graph reachability) rather than deleting them, to keep δ total. These are safe reductions before minimisation.
Alphabet reduction / character classes: many characters behave identically in δ across all states (for example all digits or all letters). Replace Σ by global equivalence classes of characters that produce identical transition targets in every state; this preserves the DFA semantics and reduces table width from |Σ| to |Σ'|. Per-state groupings can still be used as an implementation technique via defaults/compression, but they do not form a single reduced alphabet.
Transition table compression: store δ in a compressed form to reduce memory: examples include
- storing only non-default transitions together with a per-state default (default transition technique);
- base/check or displacement schemes that pack rows to a single large array (store
base[s]and for symbol x checkcheck[base[s]+code(x)]==sto accept targetnext[base[s]+code(x)]); - row displacement: place each row at an offset so that no collisions occur and store offsets. Each scheme trades memory for some extra indirection time. The base+check technique is widely used in practical scanners.
Runtime optimisations: use bitset operations or SIMD-friendly encodings for labeling transitions, use direct-threaded code or jump tables for small alphabets, and flatten action-handling so the scanner does not call complex code on every transition (delay actions until acceptance).
Lexer semantics to preserve: always implement longest-match (maximal munch) and rule priority: when multiple rules match the same lexeme, the rule with higher priority (usually earlier in the specification, or explicit priorities) wins. Optimisations must not change this behaviour.
Diagram to draw for an exam answer (describe exactly):
- Draw an NFA for regex (a|b)*abb: show start state q0, loop on a and b back to q0, then three transitions labeled a, b, b to three connected states where the final state is accepting. Label states q0,q1,q2,q3. Then to the right draw the DFA resulting from subset construction: nodes are sets like {q0}, {q0,q1}, etc. Label edges with a or b and show how some states collapse. Finally draw the DFA after minimisation with merged states; label merged set as a single state.
Formulas
|δ| = |Q| × |Σ| — number of transitions (table entries) in a full (uncompressed) DFA; |Q| is number of DFA states (unit: states), |Σ| is alphabet size (unit: symbols). Applies when table is dense and δ is total.
worst-case DFA states ≤ 2^{|Q_NFA|} — upper bound from subset construction; |Q_NFA| is number of NFA states (unit: states). Applies in worst-case pathological regexes.
Hopcroft time = O(|Σ| · |Q| · log |Q|) — with m = |Q|·|Σ| transitions this is O(m log |Q|); many texts state O(m log |Q|), and with alphabet compression m may be smaller.
default transition: δ'(s,a) = (exists explicit s→t for a ? t : default[s]) — conceptual syntax showing a per-state default if no explicit mapping exists.
Flex/flex-like rule syntax to remember:
pattern { action } — pattern is a regular expression, action is C code run when pattern matches. Rules are tried in order and longest-match is applied.
Compressed table access (base/check idiom) to remember:
index = base[s] + code(a); if check[index] == s then target = next[index] else use failure/default.
Worked examples
Subset construction then minimisation (small NFA). Regex:
ab|abb(strings "ab" or "abb").- NFA (build by hand): states q0(start) --a--> q1; q1 --b--> q2(accept for "ab"); from q2 --b--> q3(accept for "abb"). Accepting states: {q2,q3}. (No ε here.)
- Subset construction: start DFA state S0 = {q0}. On 'a' go to S1 = {q1}. On 'b' from S1 go to S2 = {q2}. From S2 on 'b' go to S3 = {q3}. From S3 on 'b' go to empty (sink). Fill missing transitions to sink. DFA states: S0,S1,S2,S3,S_sink. Accepting: S2 and S3.
- Minimise via Hopcroft (sketch): initial P = {{S2,S3},{S0,S1,S_sink}}. Process splitter {S2,S3}. Compute Pre for 'b' and 'a' to find that {S0,S1,S_sink} splits into {S1} and {S0,S_sink} because S1 on 'b' goes to S2/S3 while S0 goes to S_sink. Continue until fixed. Result: S2 and S3 are not equivalent because S2 on 'b' goes to S3 (accepting) while S3 on 'b' goes to sink (non-accepting). So final minimal DFA keeps S2 and S3 separate — no merges. This example shows systematic tracing of subsets and why minimisation may or may not merge states.
Hopcroft partition refinement example (small DFA) — show step-by-step splitting.
- DFA: Q={A,B,C,D}, Σ={a,b}, start A, accepting F={C,D}. Transitions: A: a→B, b→A B: a→C, b→D C: a→C, b→C D: a→C, b→C
- Initial P = {{C,D},{A,B}}. Put W={{C,D}}.
- Take splitter A={C,D}, symbol a: Pre_a(A) = {B,C,D} ? compute δ(x,a) ∈ {C,D}: δ(A,a)=B not in A; δ(B,a)=C in A; δ(C,a)=C in A; δ(D,a)=C in A → Pre_a(A) = {B,C,D}.
- Intersect Pre_a(A) with Y={A,B} → {B}; split {A,B} into {B} and {A}. Update P={{C,D},{B},{A}}. Add smaller split {B} to W.
- Process next symbol b and remaining splitters until W empty. Final partition merges C and D because they behave identically on both symbols and are both accepting.
- Resulting minimal DFA merges C and D into one state; states A and B remain separate.
Transition table compression (row displacement sketch). Table before:
- rows for states S0,S1,S2, columns for 'a','b','c' with many identical entries; after compression compute offsets so rows share storage; show final arrays base[], next[], check[]. Trace one lookup: for S1 and input 'b' compute index = base[S1]+code('b'); check check[index]==S1 then read next[index]. This reduces memory compared to full |Q|×|Σ| table.
(Each worked example is an exam-standard trace: list states, compute transitions, show splits/merges and final result.)
Common mistakes
- Assuming subset construction always creates few states — students forget the 2^{n} worst-case and hand-wave complexity.
- Mixing up unreachable states (remove them) with useful states reachable only via ε in the NFA: remove unreachable only after ε-closure handling.
- Incorrectly computing Pre_a(A) by testing forward rather than using inverse transitions (slower or wrong results).
- Using table compression but not updating the lexer action mapping (action indices), changing which action is invoked for an accept state.
For your exam
Typical question types: definitions (DFA, NFA, Myhill–Nerode), short notes (describe Hopcroft, table compression), derivations (prove correctness of partition refinement), algorithms (write/pseudocode Hopcroft or subset construction), traces (minimise a given DFA, compress a small table), diagrams (draw NFA→DFA→minDFA). A full-marks answer includes: precise definitions, algorithm pseudocode, assumptions (DFA total/completed), a worked trace (states, partitions, splits with values), and a final correctness statement referencing Myhill–Nerode.
Quick check
- State Myhill–Nerode equivalence relation in one sentence.
- What is the worst-case number of DFA states created by subset construction given n NFA states?
- Name two practical table-compression techniques for DFA transition tables.
Answers: 1) x ≡_L y iff for all z ∈ Σ* (xz ∈ L ⇔ yz ∈ L). 2) 2^{n}. 3) base+check (displacement) arrays and default transitions (per-state default with exceptions).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?