Sub topic 5
Converting an NFA to a DFA with Subset Construction
Prerequisites and the main idea
This chapter assumes that you know sets, functions, relations, and the definitions of deterministic finite automata (DFAs) and nondeterministic finite automata (NFAs). You should also be comfortable reading transition diagrams and processing strings symbol by symbol.
An NFA may have several possible next states for one state and input symbol. A DFA must have exactly one next state for every state and symbol. Subset construction removes this difference by making each DFA state represent a set of NFA states.
The DFA simulates all possible NFA paths at the same time. If the NFA could be in states 0 or 2 after reading a prefix, the corresponding DFA state is the set {0, 2}.
The construction
Suppose an NFA has state set Q, alphabet Σ, start state q₀, accepting states F, and transition function δ. The DFA is built as follows:
- The DFA start state is {q₀}.
- For a set S of NFA states and symbol a, define the DFA transition as
δD(S, a) = the union of δ(q, a) for every q in S.
- Repeat this process for every newly discovered set.
- A DFA set S is accepting if S contains at least one NFA accepting state.
- Include the empty set if a transition reaches it. It becomes a dead state whose transitions remain empty.
Only reachable subsets need to be created. Although an NFA with n states can produce as many as 2ⁿ DFA states, many subsets are often unreachable.
Worked example
Consider an NFA with start state 0, accepting state 3, and transitions:
| NFA state set | On a | On b |
|---|---|---|
| {0} | {0,1} | {0} |
| {0,1} | {0,1} | {0,2} |
| {0,2} | {0,1} | {0,3} |
| {0,3} | {0,1} | {0} |
The reachable DFA states are {0}, {0,1}, {0,2}, and {0,3}. The last set is accepting because it contains NFA state 3. For example, from {0,1} on b, the NFA can move from 0 to 0 and from 1 to 2. Their union is {0,2}.
The NFA accepts a string whenever at least one possible path ends in state 3. The DFA records that condition by accepting whenever its current subset contains 3.
from collections import deque
nfa = {
(0, "a"): {0, 1},
(0, "b"): {0},
(1, "b"): {2},
(2, "b"): {3},
}
def subset_construction(start, accepting, alphabet):
first = frozenset({start})
seen = {first}
queue = deque([first])
transitions = {}
while queue:
subset = queue.popleft()
for symbol in alphabet:
target = frozenset(
state
for source in subset
for state in nfa.get((source, symbol), set())
)
transitions[(subset, symbol)] = target
if target not in seen:
seen.add(target)
queue.append(target)
dfa_accepting = {subset for subset in seen if subset & accepting}
return seen, transitions, dfa_accepting
states, transitions, accepting = subset_construction(0, {3}, "ab")
print(len(states)) # 4
print(accepting) # {frozenset({0, 3})}Exercise
An NFA starts in state 0. On symbol a, state 0 can move to states 0 and 1. What DFA state represents the possible states after reading a?
Show answer
The DFA state is {0,1}.