Skip to main content

02 - DFA, NFA, ε-NFA: Equivalences and Thompson Construction

From expression to DFA: Thompson construction, subsets and minimization, with the states counted and the cost of backtracking measured.

What do you think about this article?

02 - DFA, NFA, ε-NFA: Equivalences and Thompson Construction
Formal Languages & Compilersfedericocalo.dev

At a Glance

From expression to DFA: Thompson construction, subsets and minimization, with the states counted and the cost of backtracking measured.

You have written a regular expression and an engine runs it: but what does it do, exactly, with your string? Behind almost every engine there is a finite-state automaton, and there is a basic choice between two ways of running it: simulate all the possible paths together, or try them one at a time and backtrack. This article builds the automaton from the expression, turns it into a deterministic machine, reduces it to the minimum, and measures what each step costs. In short: DFAs, NFAs and ε-NFAs recognize the same languages; Thompson's construction produces an ε-NFA whose size is linear in the expression; determinization can cost an exponential number of states; minimization gives the smallest possible automaton.

This is the second article in the Formal Languages and Compilers series; it assumes the first, whose file regex_ast.py (the parser and the semantics of expressions) we reuse. All the listings were run with Python 3.14.4 on an AMD Ryzen 5 5600H; the deterministic outputs are identical across two consecutive runs, the timing one is reported as an interval.

Three kinds of machine, one expressive power

A DFA (deterministic automaton) is a quintuple (Q, Σ, δ, q0, F): states, alphabet, transition function δ : Q × Σ → Q, initial state, final states. For every state and every symbol there is exactly one move, so for every string there is a single path. An everyday example is the check "does it end with abb?": four states, which remember how much of abb you have read in the last few characters (none, a, ab, abb), and one transition for each of the two symbols. After each character the automaton only knows which of the four states it is in, and that is enough.

An NFA (nondeterministic) has δ : Q × Σ → 2Q: from a state, reading a symbol, it can go to zero, one or more states, and it accepts if at least one of the paths ends in a final state. An ε-NFA adds moves that consume no input. Every DFA is an NFA and every NFA is an ε-NFA, so the easy direction of the equivalence is free; the other direction, from ε-NFA to DFA, is the determinization we build below. Nondeterminism is not a machine that "guesses": it is a compact way of describing a set of paths, and any simulation translates it into "keep track of all the states you might be in".

Thompson's construction

Thompson's construction turns an expression into an ε-NFA by following its structure, one automaton fragment for each node of the syntax tree. Every fragment has a single initial state and a single final state, and that is how the pieces fit together without ambiguity.

  • symbol a (and likewise ε): two states and an edge labelled a from one to the other;
  • concatenation RS: an ε edge from the final state of R to the initial state of S;
  • alternation R|S: a new initial state with two ε edges to the initial states of the two fragments, a new final state reached with ε edges from the two final states;
  • star R*: a new initial state and a new final state, with ε edges to enter R, to skip it altogether, and to repeat it from its exit.

The four rules are not in order of importance and could be listed in any sequence; what holds them together is their uniformity. They add states only for symbols, alternations and stars (two each): concatenation adds none, and that is why the number of states grows linearly with the size of the expression. There are variants that merge states and use fewer, so the count depends on the variant: what I report is for the variant of the listing, with an ε edge between concatenated fragments.

The listing thompson.py encodes the four rules in the inner function costruisci: each case returns (start, end, edges) of its own fragment, and ε edges are the tuples with None in place of the symbol. The final block builds the automaton for seven expressions and checks four properties: the number of states equals 2 × (symbols + ε + alternations + stars), no state has more than two outgoing edges, the final state has no outgoing edges, and no edge enters the initial state.

# thompson.py - Thompson's construction: expression -> epsilon-NFA
from regex_ast import parse

def thompson(node):
    """Returns (start, end, edges): edges = list of (from, symbol|None, to)."""
    contatore = [0]

    def nuovo():
        contatore[0] += 1
        return contatore[0] - 1

    def costruisci(n):
        tipo = n[0]
        if tipo == 'eps':
            s, f = nuovo(), nuovo()
            return s, f, [(s, None, f)]
        if tipo == 'char':
            s, f = nuovo(), nuovo()
            return s, f, [(s, n[1], f)]
        if tipo == 'cat':
            s1, f1, a1 = costruisci(n[1])
            s2, f2, a2 = costruisci(n[2])
            return s1, f2, a1 + a2 + [(f1, None, s2)]
        if tipo == 'alt':
            s1, f1, a1 = costruisci(n[1])
            s2, f2, a2 = costruisci(n[2])
            s, f = nuovo(), nuovo()
            return s, f, a1 + a2 + [(s, None, s1), (s, None, s2), (f1, None, f), (f2, None, f)]
        s1, f1, a1 = costruisci(n[1])               # star
        s, f = nuovo(), nuovo()
        return s, f, a1 + [(s, None, s1), (s, None, f), (f1, None, s1), (f1, None, f)]

    return costruisci(node)

def conta(node):
    tipi = []
    def visita(n):
        tipi.append(n[0])
        for figlio in n[1:]:
            if isinstance(figlio, tuple):
                visita(figlio)
    visita(node)
    return tipi

if __name__ == '__main__':
    for espr in ['a', 'ab', 'a|b', 'a*', '(a|b)*c', '(a|b)*abb', '((a*)*b*)*']:
        ast = parse(espr)
        inizio, fine, archi = thompson(ast)
        stati = {inizio, fine} | {s for s, _, _ in archi} | {t for _, _, t in archi}
        tipi = conta(ast)
        previsti = 2 * (tipi.count('char') + tipi.count('eps') + tipi.count('alt') + tipi.count('star'))
        uscenti = {s: sum(1 for x, _, _ in archi if x == s) for s in stati}
        entranti_inizio = sum(1 for _, _, t in archi if t == inizio)
        print(f'{espr:12} states={len(stati):2} expected={previsti:2}  edges={len(archi):2}  '
              f'max outgoing={max(uscenti.values())}  outgoing from the final state={uscenti[fine]}  '
              f'incoming to the initial state={entranti_inizio}')

# Output:
# a            states= 2 expected= 2  edges= 1  max outgoing=1  outgoing from the final state=0  incoming to the initial state=0
# ab           states= 4 expected= 4  edges= 3  max outgoing=1  outgoing from the final state=0  incoming to the initial state=0
# a|b          states= 6 expected= 6  edges= 6  max outgoing=2  outgoing from the final state=0  incoming to the initial state=0
# a*           states= 4 expected= 4  edges= 5  max outgoing=2  outgoing from the final state=0  incoming to the initial state=0
# (a|b)*c      states=10 expected=10  edges=12  max outgoing=2  outgoing from the final state=0  incoming to the initial state=0
# (a|b)*abb    states=14 expected=14  edges=16  max outgoing=2  outgoing from the final state=0  incoming to the initial state=0
# ((a*)*b*)*   states=12 expected=12  edges=19  max outgoing=2  outgoing from the final state=0  incoming to the initial state=0

For (a|b)*c the three symbols, the alternation and the star give 2·(3+1+1) = 10 states, and the program counts exactly 10. The four properties hold on all seven expressions, including deliberately extravagant ones like ((a*)*b*)* (12 states, 19 edges). The maximum of two outgoing edges per state is what makes the simulation predictable: a step cannot fork into more than two roads per state.

Simulating the automaton by keeping track of all the states

To make an NFA accept or reject a string you do not need to try the paths one by one: it is enough to keep the set of states you might be in. Before reading a character, and after every move, you extend that set with its ε-closure, that is, all the states reachable without consuming input. A concrete example: for (a|b)*c, the initial set contains not only the initial state of the star, but also the entry of the alternation and the state from which you exit towards c, because from there you can start without reading anything.

In the file simulazione.py, chiusura is a depth-first visit along the ε edges only, while accetta alternates for each character a move (mosse.get((s, c))) and a closure. The string is accepted if the final state is among the active ones at the end. The independent check is Python's re.fullmatch (documentation): on seven expressions and on all strings up to length 9, up to 29,524 for the three-symbol alphabet, they must agree.

# simulazione.py - simulation of the epsilon-NFA, compared with the re module
import re
from itertools import product
from regex_ast import parse
from thompson import thompson

def prepara(espr):
    inizio, fine, archi = thompson(parse(espr))
    eps, mosse = {}, {}
    for s, c, t in archi:
        (eps if c is None else mosse).setdefault((s, c) if c else s, set()).add(t)
    return inizio, fine, eps, mosse

def chiusura(insieme, eps):
    """epsilon-closure: all the states reachable without reading input."""
    pila, visti = list(insieme), set(insieme)
    while pila:
        for t in eps.get(pila.pop(), ()):
            if t not in visti:
                visti.add(t)
                pila.append(t)
    return frozenset(visti)

def accetta(nfa, w):
    inizio, fine, eps, mosse = nfa
    attivi = chiusura({inizio}, eps)
    for c in w:
        passo = set()
        for s in attivi:
            passo |= mosse.get((s, c), set())
        attivi = chiusura(passo, eps)
    return fine in attivi

if __name__ == '__main__':
    N = 9
    casi = [('(a|b)*abb', 'ab'), ('(a|b)*a(a|b)', 'ab'), ('(0|1)*01(0|1)*', '01'),
            ('(ab|a)*', 'ab'), ('((a*)*b*)*', 'ab'), ('a(b|())*', 'ab'), ('(a|b)*c', 'abc')]
    for espr, alfabeto in casi:
        nfa = prepara(espr)
        tutte = [''.join(t) for k in range(N + 1) for t in product(alfabeto, repeat=k)]
        errori = sum(accetta(nfa, w) != bool(re.fullmatch(espr, w)) for w in tutte)
        print(f'{espr:16} strings={len(tutte):5}  disagreements with re: {errori}')

# Output:
# (a|b)*abb        strings= 1023  disagreements with re: 0
# (a|b)*a(a|b)     strings= 1023  disagreements with re: 0
# (0|1)*01(0|1)*   strings= 1023  disagreements with re: 0
# (ab|a)*          strings= 1023  disagreements with re: 0
# ((a*)*b*)*       strings= 1023  disagreements with re: 0
# a(b|())*         strings= 1023  disagreements with re: 0
# (a|b)*c          strings=29524  disagreements with re: 0

Zero disagreements on seven expressions. The active states are at most all those of the automaton, which in Thompson's automaton are linear in the expression: Russ Cox, in "Regular Expression Matching Can Be Simple And Fast", observes that an automaton of n nodes cannot have more than n reachable states at each step even though the paths can be 2n. That is why the cost of the simulation grows linearly with the length of the input, for a fixed expression, instead of exploding.

Determinizing: the subset construction

If the simulation keeps a set of states, why not make that set directly a state of a new automaton? That is the subset construction: the states of the DFA are sets of states of the NFA, the initial state is the ε-closure of the initial state, and from the set-state S with the symbol c you go to the ε-closure of all the states reached from an element of S. A set-state is final if it contains the final state of the NFA. You build only the sets reachable from the initial one, not all the 2n possible ones.

In sottoinsiemi.py, determinizza keeps a stack of sets to expand. If from a set you cannot go anywhere, the empty set becomes the sink state, which lets the DFA be total, that is, always have a move. The final block compares the resulting automaton with re on all strings up to length 10, and prints the number of states and whether the sink appears.

# sottoinsiemi.py - determinization: from the epsilon-NFA to the DFA
import re
from itertools import product
from simulazione import prepara, chiusura

def determinizza(espr, alfabeto):
    inizio, fine, eps, mosse = prepara(espr)
    s0 = chiusura({inizio}, eps)
    stati, delta, da_fare = {s0}, {}, [s0]
    while da_fare:
        S = da_fare.pop()
        for c in alfabeto:
            passo = set()
            for q in S:
                passo |= mosse.get((q, c), set())
            T = chiusura(passo, eps)                 # may be empty: the "sink" state
            delta[(S, c)] = T
            if T not in stati:
                stati.add(T)
                da_fare.append(T)
    accetti = {S for S in stati if fine in S}
    return stati, delta, s0, accetti

def accetta(dfa, w):
    stati, delta, s0, accetti = dfa
    S = s0
    for c in w:
        S = delta[(S, c)]
    return S in accetti

if __name__ == '__main__':
    N = 10
    casi = [('(a|b)*abb', 'ab'), ('(a|b)*a(a|b)', 'ab'), ('(0|1)*01(0|1)*', '01'),
            ('(ab|a)*', 'ab'), ('(a|b)*c', 'abc')]
    for espr, alfabeto in casi:
        dfa = determinizza(espr, alfabeto)
        tutte = [''.join(t) for k in range(N + 1) for t in product(alfabeto, repeat=k)]
        errori = sum(accetta(dfa, w) != bool(re.fullmatch(espr, w)) for w in tutte)
        pozzo = frozenset() in dfa[0]
        print(f'{espr:16} DFA states={len(dfa[0]):2}  with sink state: {pozzo!s:5}  disagreements with re: {errori}')

# Output:
# (a|b)*abb        DFA states= 5  with sink state: False  disagreements with re: 0
# (a|b)*a(a|b)     DFA states= 5  with sink state: False  disagreements with re: 0
# (0|1)*01(0|1)*   DFA states= 7  with sink state: False  disagreements with re: 0
# (ab|a)*          DFA states= 4  with sink state: True   disagreements with re: 0
# (a|b)*c          DFA states= 5  with sink state: True   disagreements with re: 0

No disagreement on five expressions. The number of states is not the minimum, however: (a|b)*abb has 5 states here, but the DFA written by hand in article 01 had 4. The difference is not an error, it is a property of the construction, which does not recognize by itself when two sets behave identically. The sink appears where the expression can "break": in (a|b)*c, after a c any other symbol sends the automaton into a state from which nothing is accepted anymore.

What determinizing costs, and how to reduce it

The interesting question is the growth of the number of states. To answer it I use a family of expressions, Ln = (a|b)*a(a|b)n-1, that is, the strings whose n-th symbol from the end is an a. Thompson's NFA for Ln is small and linear in n. To decide whether the string is in Ln, however, a DFA must remember the last n symbols read, which are 2n possibilities.

This is proved with the Myhill-Nerode classes, introduced in article 01. Take two different strings x and y of length n, which differ at position i, with xi = a and yi = b. Append the suffix z = bi-1: the word xz has its n-th symbol from the end equal to xi = a, so it is in Ln, while yz has a b in that position and is not. The 2n strings of length n therefore fall into 2n distinct classes, and every DFA for Ln has at least 2n states.

To bring the DFA to the minimum I use Moore's refinement, in the file minimizza.py: I start from the partition of the states into final and non-final, and at each round I separate the states that have at least one successor in different blocks for some symbol, until the partition no longer changes. The number of final blocks is the number of states of the minimal DFA. The table compares, for n from 1 to 7, the states of the NFA, those of the subset DFA and those of the minimal DFA; for n ≤ 5 it adds a second, independent computation, the Myhill-Nerode classes estimated on short prefixes and suffixes (that computation does not use automata).

# minimizza.py - minimization by partition refinement (Moore)
from itertools import product
from regex_ast import parse
from thompson import thompson
from sottoinsiemi import determinizza, accetta

def moore(dfa, alfabeto):
    stati, delta, s0, accetti = dfa
    blocco = {S: (S in accetti) for S in stati}            # initial partition: final / non-final
    while True:
        firma = {S: (blocco[S],) + tuple(blocco[delta[(S, c)]] for c in alfabeto) for S in stati}
        nomi = {f: i for i, f in enumerate(sorted(set(firma.values()), key=repr))}
        nuovo = {S: nomi[firma[S]] for S in stati}
        if len(set(nuovo.values())) == len(set(blocco.values())):
            return len(set(nuovo.values()))
        blocco = nuovo

def stati_nfa(espr):
    inizio, fine, archi = thompson(parse(espr))
    return len({inizio, fine} | {x for a in archi for x in (a[0], a[2])})

def classi_mn(espr_accetta, alfabeto, n):
    """Myhill-Nerode classes estimated with prefixes and suffixes of length at most n."""
    parole = [''.join(t) for k in range(n + 1) for t in product(alfabeto, repeat=k)]
    return len({frozenset(z for z in parole if espr_accetta(x + z)) for x in parole})

if __name__ == '__main__':
    print('  n  NFA(Thompson)  DFA(subsets)  minimal DFA  Myhill-Nerode classes')
    for n in range(1, 8):
        espr = '(a|b)*a' + '(a|b)' * (n - 1)
        dfa = determinizza(espr, 'ab')
        mn = classi_mn(lambda w: accetta(dfa, w), 'ab', n + 1) if n <= 5 else '-'
        print(f'{n:3}  {stati_nfa(espr):13}  {len(dfa[0]):12}  {moore(dfa, "ab"):11}  {mn}')
    for espr, alfabeto in [('(a|b)*abb', 'ab'), ('(a|b)*c', 'abc'), ('(a|b)*', 'ab')]:
        dfa = determinizza(espr, alfabeto)
        print(f'{espr:10} DFA={len(dfa[0])}  minimal={moore(dfa, alfabeto)}')

# Output:
#   n  NFA(Thompson)  DFA(subsets)  minimal DFA  Myhill-Nerode classes
#   1             10             3            2  2
#   2             16             5            4  4
#   3             22             9            8  8
#   4             28            17           16  16
#   5             34            33           32  32
#   6             40            65           64  -
#   7             46           129          128  -
# (a|b)*abb  DFA=5  minimal=4
# (a|b)*c    DFA=5  minimal=3
# (a|b)*     DFA=3  minimal=1

The numbers say three things. The states of the NFA grow by 6 at each step (10, 16, 22, …, 46); the minimal DFA is exactly 2n (2, 4, 8, …, 128), in agreement with the proof, and the Myhill-Nerode classes coincide with the minimum where I computed them; the subset DFA has 2n + 1 states, one more, because the construction keeps the initial state separate from the equivalent one in which you end up after reading any character. The (a|b)* row shows the effect in miniature: three states after determinization, a single one after minimization. The "2n + 1" is a measurement for n from 1 to 7, not a theorem.

Moore's refinement is simple and correct, but it is not the fastest algorithm: at each round it scans all the states, and the rounds are at most as many as the states, so the cost is quadratic in the worst case. Faster algorithms exist, such as Hopcroft's, which I have neither implemented nor measured here. A fact more relevant to everyday work: the minimal DFA of a language is unique up to renaming the states, so two expressions are equivalent if and only if they have the same minimal DFA, and it is a way of deciding equivalence of which the enumeration in article 01 is a partial version.

Why real engines are not all the same

Simulating the NFA or determinizing are two ways of never going back. An engine with backtracking instead picks a road, follows it, and if it fails goes back to the last choice and tries another. With "pure" regular expressions it gives the same result; the time, instead, can explode. The textbook case, presented by Cox, is a?nan applied to the string an: each a? can consume or skip an a, and an engine with backtracking explores the combinations. Here I write a? as (a|()), because my parser has no ? operator.

The listing measures Python's re engine and my NFA simulation on the same pattern, for n from 16 to 24. The first column of numbers is subject to machine noise: over eight consecutive runs I measured, for re, about 3-21 ms for n=16, 10-56 ms for n=18, 41-259 ms for n=20, 0.19-0.78 s for n=22 and 0.77-2.2 s for n=24; the NFA simulation took 0.3-1.1 ms in all cases. From the time of re I infer that for every pair of extra n the time is multiplied by about four: consistent with exponential growth, not a proof (there are only five points).

# backtracking.py - the same pattern, two strategies: backtracking in re and NFA simulation
import re
import time
from simulazione import prepara, accetta

def tempo(f):
    t0 = time.perf_counter()
    f()
    return time.perf_counter() - t0

for n in (16, 18, 20, 22, 24):
    espr = '(a|())' * n + 'a' * n        # the pattern a?^n a^n (with ()=epsilon), on the string a^n
    w = 'a' * n
    t_re = tempo(lambda: re.fullmatch(espr, w))
    nfa = prepara(espr)
    t_nfa = tempo(lambda: accetta(nfa, w))
    print(f'n={n}: re {t_re:.4f} s, NFA simulation {t_nfa:.4f} s, '
          f'accepted by re: {re.fullmatch(espr, w) is not None}, by the simulation: {accetta(nfa, w)}')

# Output of one run (the times change from one run to the next):
# n=16: re 0.0074 s, NFA simulation 0.0006 s, accepted by re: True, by the simulation: True
# n=18: re 0.0323 s, NFA simulation 0.0035 s, accepted by re: True, by the simulation: True
# n=20: re 0.1393 s, NFA simulation 0.0037 s, accepted by re: True, by the simulation: True
# n=22: re 0.6060 s, NFA simulation 0.0007 s, accepted by re: True, by the simulation: True
# n=24: re 2.8869 s, NFA simulation 0.0009 s, accepted by re: True, by the simulation: True

At n = 24 the string is 24 characters long, and the backtracking engine takes up to a few seconds while the simulation stays below a millisecond. This does not mean that the re module is "wrong": it accepts features, such as backreferences, that leave the regular languages (article 01) and for which, according to Cox, the best known implementations require an exponential search in the worst case. It means that if you accept expressions from untrusted sources, and you do not need those extensions, a linear-time engine protects you from an expression built to block you. I measured a single engine on a single family of expressions: I did not measure RE2 or other engines.

Here is what you can do now. You can turn an expression into an ε-NFA with Thompson's construction and count its states; you can simulate the automaton with the ε-closure and check the simulation against an independent engine; you can determinize by subsets and you know why the result can have 2n states; you can minimize with Moore's refinement and recognize a minimal DFA from the Myhill-Nerode classes. In the next article you leave the regular languages behind with context-free grammars.

Frequently asked questions

Is an NFA more powerful than a DFA?

No: they recognize the same languages. Nondeterminism is more compact, not more expressive: the subset construction turns any NFA into an equivalent DFA, at the price of a number of states that for the family measured here grows like 2n.

How many states does Thompson's NFA have for an expression?

In the variant of the listing, two for each symbol, ε, alternation and star; concatenation adds none. For (a|b)*c that is 10. Other variants merge states and use fewer, so the number depends on the variant.

Why can Python's re module be slow on certain expressions?

Because it tries the paths one at a time and goes back when it fails: on expressions like (a?)nan the number of combinations grows exponentially. The NFA simulation keeps track of all the states together and never goes back.

The same series also includes article 04, top-down parsers, article 05, bottom-up parsers and article 06, semantic analysis and optimization.

Sources

Previous article: 01 - Regular Expressions and Regular Languages. Next article: 03 - Context-Free Grammars and Non-Regular Languages. The index is on the series page.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects