Sub topic 5
From regular expression to NFA to DFA
This chapter assumes you know what a regular expression, an NFA and a DFA are, and that you can read a transition table. It shows the pipeline a lexer generator follows: a regular expression becomes an NFA, the NFA becomes a DFA, and the DFA gets minimized.
The pipeline
A DFA is fast because it does one table lookup per character. A regular expression is easy to write but not directly executable. An NFA sits in between, because it can be built mechanically from the expression's structure. The usual route is:
- Build an NFA with ε-transitions using Thompson's construction.
- Convert it to a DFA using the subset construction.
- Optionally minimize the DFA.
Thompson's construction
Thompson's construction builds the NFA bottom-up. Each piece has one start state and one accepting state.
| Expression | Construction | Column |
|---|---|---|
| ε | start state, an ε-edge to the accepting state | |
| a | start state, an edge labelled a to the accepting state | |
| r\ | s | new start with ε-edges to the starts of r and s; ε-edges from both accepting states to a new accepting state |
| rs | the accepting state of r is merged with the start of s | |
| r* | new start and new accepting state; ε-edges for entering r, for looping back, and for skipping r |
The construction has properties that GATE questions often use:
- The NFA has at most 2n states, where n is the number of symbols and operators in the expression.
- It has exactly one start state and one accepting state.
- The start state has no incoming edges, and the accepting state has no outgoing edges.
- Every state has either one outgoing edge on a symbol, or at most two outgoing ε-edges.
Subset construction
Each DFA state is a set of NFA states. Two operations drive the algorithm:
- ε-closure(S) is the set of NFA states reachable from any state in S using only ε-edges, including S itself.
- move(S, a) is the set of NFA states reachable from S by one edge labelled a.
The algorithm runs as follows:
- The DFA start state is ε-closure({NFA start}).
- For each unmarked DFA state S and each symbol a, compute U = ε-closure(move(S, a)).
- If U is non-empty and new, add it as a DFA state. Record the transition S on a to U.
- A DFA state is accepting if it contains any accepting NFA state.
The empty set is not a state. It becomes the missing transition, or a dead state if you want a complete DFA.
Worked example: (a|b)*abb
An NFA for strings over {a, b} ending in abb has states 0 to 3. State 0 loops on a and b, 0 goes to 1 on a, 1 goes to 2 on b, and 2 goes to 3 on b. State 3 is accepting. Thompson's construction would give about 11 states with ε-edges. This hand-built form has no ε-edges, so the closure step does nothing here.
Running the subset construction gives these DFA states:
- A = {0}
- B = {0,1}
- C = {0,2}
- D = {0,3}, which is accepting
| DFA state | on a | on b |
|---|---|---|
| A = {0} | B | A |
| B = {0,1} | B | C |
| C = {0,2} | B | D |
| D = {0,3} | B | A |
Running the subset construction in code
EPS = ""
def eps_closure(nfa, states):
closure = set(states)
stack = list(states)
while stack:
s = stack.pop()
for t in nfa.get((s, EPS), ()):
if t not in closure:
closure.add(t)
stack.append(t)
return frozenset(closure)
def move(nfa, states, symbol):
return {t for s in states for t in nfa.get((s, symbol), ())}
def subset_construction(nfa, start, accepting, alphabet):
d0 = eps_closure(nfa, {start})
names = {d0: 0}
work = [d0]
dfa = {}
while work:
S = work.pop()
for a in alphabet:
U = eps_closure(nfa, move(nfa, S, a))
if not U:
continue
if U not in names:
names[U] = len(names)
work.append(U)
dfa[(names[S], a)] = names[U]
accept = {n for S, n in names.items() if S & accepting}
return dfa, accept, names
def run(dfa, accept, text):
state = 0
for ch in text:
state = dfa.get((state, ch))
if state is None:
return False
return state in accept
nfa = {
(0, "a"): {0, 1},
(0, "b"): {0},
(1, "b"): {2},
(2, "b"): {3},
}
dfa, accept, names = subset_construction(nfa, 0, {3}, "ab")
for S, n in sorted(names.items(), key=lambda kv: kv[1]):
print(n, sorted(S))
print(run(dfa, accept, "aabb"), run(dfa, accept, "abab"), run(dfa, accept, "babb"))
# True False TrueThe printed subsets are {0}, {0,1}, {0,2} and {0,3}, numbered 0 to 3. These match A to D in the table.
Edge cases and state blow-up
- Worst case. An NFA with n states can need up to 2^n DFA states. The language "the n-th symbol from the end is a" has an (n+1)-state NFA, but its minimal DFA needs 2^n states. Most real token patterns do not behave this way.
- Number of reachable states. The construction only creates subsets reachable from the start. The count is often far below 2^n, and GATE questions usually ask for exactly this count.
- ε-closure on the start state. Forgetting it is the most common error. If the NFA's start state has ε-edges, the DFA start state contains more than just the start state.
- Accepting states. A DFA state is accepting if it contains any NFA accepting state, not only when all of its NFA states are accepting.
Minimizing the DFA
Two DFA states are equivalent if no string distinguishes them, meaning no string leads one to acceptance and the other to rejection. Partition refinement finds the equivalent states:
- Split the states into accepting and non-accepting groups.
- Split a group when two of its states go to different groups on some symbol.
- Repeat until no group splits. Each remaining group becomes one state.
The DFA above is already minimal. A is separated from C because C on b reaches the accepting group and A does not. B is separated from A because B on b reaches C and A on b reaches A, which are in different groups after the second round. The minimal DFA for a regular language is unique up to renaming of states.
For a lexer, the accepting states must also be kept apart by token class. If two token patterns are merged into one DFA, a state that accepts "keyword" and a state that accepts "identifier" are different even if their outgoing edges match.
Exercise
An NFA has states {0,1,2} with start 0, accepting state 2, and these edges: 0 -ε-> 1, 1 -a-> 1, 1 -ε-> 2, 2 -b-> 0. Give the DFA start state and say whether it is accepting.
Show answer
The start state is ε-closure({0}). From 0 the ε-edge reaches 1, and from 1 the ε-edge reaches 2, so the closure is {0,1,2}. It contains the accepting NFA state 2, so the DFA start state is accepting. The empty string is therefore in the language.
Exercise
For the DFA of (a|b)*abb above, which state does the input "abbabb" end in, and is it accepted?
Show answer
The path is A, B, C, D, B, C, D. The final state is D, which is accepting, so the string is accepted.