Skip to content
Part IA Michaelmas, Lent Term

NFA and DFA Examples

Example 1: Contains “aaa”

NFA

NFA accepting strings over {a,b}\{a, b\} containing three consecutive aa‘s:

NFA for contains aaa

  • Q={q0,q1,q2,q3}Q = \{q_0, q_1, q_2, q_3\}
  • Transitions:
    • q0a,bq0q_0 \xrightarrow{a,b} q_0 (stay until we start counting)
    • q0aq1q_0 \xrightarrow{a} q_1 (first aa)
    • q1aq2q_1 \xrightarrow{a} q_2 (second aa)
    • q2aq3q_2 \xrightarrow{a} q_3 (third aa, accept)
    • q3a,bq3q_3 \xrightarrow{a,b} q_3 (stay accepting)
  • F={q3}F = \{q_3\}

DFA Equivalent

Via subset construction, the DFA has up to 24=162^4 = 16 states, but many are unreachable.

Example 2: Contains “ab” as Substring

NFA

NFA for contains ab

Intuitively: stay in q0q_0, transition to q1q_1 on aa, then to q2q_2 on bb, stay in q2q_2.

DFA

DFA for contains ab

  • Q={q0,q1,q2}Q = \{q_0, q_1, q_2\}
  • Transitions:
Stateaabb
q0q_0q1q_1q0q_0
q1q_1q1q_1q2q_2
q2q_2q2q_2q2q_2

F={q2}F = \{q_2\}

Example 3: Modulo Counter

DFA: Divisible by 4 (Binary)

Accepts binary strings divisible by 4:

DFA for divisible by 4

  • Q={q0,q1,q2,q3}Q = \{q_0, q_1, q_2, q_3\} (remainder mod 4)
  • δ(qr,0)=q(2r)mod4\delta(q_r, 0) = q_{(2r) \bmod 4}
  • δ(qr,1)=q(2r+1)mod4\delta(q_r, 1) = q_{(2r+1) \bmod 4}
  • F={q0}F = \{q_0\}

Intuition

Reading binary left-to-right:

  • Append 0: multiply by 2
  • Append 1: multiply by 2, add 1

Example 4: Exact Pattern

DFA: Exactly “ab”

DFA for exactly ab

  • Q={q0,q1,q2,qd}Q = \{q_0, q_1, q_2, q_d\}
  • Transitions:
Stateaabb
q0q_0q1q_1qdq_d
q1q_1qdq_dq2q_2
q2q_2qdq_dqdq_d
qdq_dqdq_dqdq_d

F={q2}F = \{q_2\}

Dead state qdq_d ensures no other strings are accepted.

Example 5: At Most Two aa‘s

DFA

Accepts strings with at most two aa‘s:

  • Q={q0,q1,q2,q3}Q = \{q_0, q_1, q_2, q_3\}
  • States track how many aa‘s seen so far
  • qiq_i: seen exactly ii aa‘s
  • q3q_3: seen three or more aa‘s (rejecting trap)
Stateaabb
q0q_0q1q_1q0q_0
q1q_1q2q_2q1q_1
q2q_2q3q_3q2q_2
q3q_3q3q_3q3q_3

F={q0,q1,q2}F = \{q_0, q_1, q_2\}

Example 6: Union via NFA-ε\varepsilon

Languages

L1={w:w ends in a}L_1 = \{w : w \text{ ends in } a\}

L2={w:w ends in b}L_2 = \{w : w \text{ ends in } b\}

NFA-ε\varepsilon for L1L2L_1 \cup L_2

Create new start with ε\varepsilon-transitions to both machines:

Union NFA-epsilon example

Accepting: both F1F_1 and F2F_2.


Summary

  • NFAs are easier to construct for pattern detection
  • DFAs are canonical (unique minimal DFA)
  • Union uses epsilon transitions in NFAs
  • Counting/modulo uses state to track remainder