---
title: "Finite Automata"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 21
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 21 — Finite Automata

Is a typed string a decimal number, such as `-12.5e3`? A program can decide with one table and one loop:

```rust
// dfa_demo.rs: is the string a decimal number such as -12.5e3? One table and one loop.
const START: usize = 0;
const ACCEPT: [bool; 8] = [false, false, true, false, true, false, false, true];
// columns: digit, sign, point, e or E; rows: the 8 states; NO: no transition
const NO: usize = usize::MAX;
const TABLE: [[usize; 4]; 8] = [
    [2, 1, NO, NO],  // 0 start
    [2, NO, NO, NO], // 1 after the sign
    [2, NO, 3, 5],   // 2 in the integer part (accepting)
    [4, NO, NO, NO], // 3 after the point
    [4, NO, NO, 5],  // 4 in the fraction (accepting)
    [7, 6, NO, NO],  // 5 after the e
    [7, NO, NO, NO], // 6 after the exponent's sign
    [7, NO, NO, NO], // 7 in the exponent (accepting)
];

pub fn class(c: char) -> Option<usize> {
    match c {
        '0'..='9' => Some(0),
        '+' | '-' => Some(1),
        '.' => Some(2),
        'e' | 'E' => Some(3),
        _ => None,
    }
}

pub fn is_number(s: &str) -> (bool, Vec<usize>) {
    let (mut q, mut path) = (START, vec![START]);
    for c in s.chars() {
        match class(c).map(|k| TABLE[q][k]) {
            Some(next) if next != NO => q = next,
            _ => return (false, path), // no transition: rejected at once
        }
        path.push(q);
    }
    (ACCEPT[q], path)
}
```

***Listing 21.1.** A decimal number recogniser: eight states, four classes of characters code/bachelor-2/21-finite-automata/listings/dfa_demo.rs*

```
$ rustc --edition 2021 -O -o dfa_demo dfa_demo.rs && ./dfa_demo
"-12.5e3"  number   states 0 1 2 2 3 4 5 7
"+0.25E-7" number   states 0 1 2 3 4 4 5 6 7
"42"       number   states 0 2 2
"3."       no       states 0 2 3
".5"       no       states 0
"1e"       no       states 0 2 5
"12a"      no       states 0 2 2
"--1"      no       states 0 1
""         no       states 0
```

***Output 21.1.** Nine strings and the states they visit.*

The program remembers nothing about the string but one number from 0 to 7, its *state*, and it reads each character once. Such a device is a *finite automaton*. This chapter defines automata exactly, gives them a power they seem to lack, guessing, shows that guessing adds nothing but costs states, sometimes exponentially many, and builds automata for combinations of conditions. The next chapter connects them with the patterns of regular expressions, and finds what no finite automaton can do.

**You already know.**

The Year 1 volume: a finite-state machine has a finite set of states, a start state, and a [transition function](#def-b2-finite-automata-dfa) from a state and an input to the next state; it may also produce outputs. Proofs by induction on the length of a [word](#def-b2-finite-automata-word), or by structural induction. Sets, maps, and the set of subsets of a set, which has $2^n$ elements when the set has $n$.

## 21.1 Words and languages

**Definition 21.1 (Alphabet, word).**

An *alphabet* is a finite nonempty set $\Sigma$, whose elements are *letters*. A *word* over $\Sigma$ is a finite sequence of letters $w = a_1 a_2 \cdots a_n$; its *length* is $|w| = n$. The *empty word* $\varepsilon$ has length 0. The set of all words is $\Sigma^*$, and there are $|\Sigma|^n$ words of length $n$.

The *concatenation* of $u$ and $v$ is the [word](#def-b2-finite-automata-word) $uv$, $u$ followed by $v$: it is associative, $\varepsilon$ is neutral, and $|uv| = |u| + |v|$. In the hook, $\Sigma$ is the set of characters, and the program reads `"-12.5e3"` as a [word](#def-b2-finite-automata-word) of length 7.

**Definition 21.2 (Language).**

A *language* over $\Sigma$ is a set of [words](#def-b2-finite-automata-word), finite or infinite. For languages $L$ and $M$, the *concatenation* is $LM = \{uv : u \in L,\ v \in M\}$; the *powers* are $L^0 = \{\varepsilon\}$ and $L^{n+1} = L^n L$; and the *star* of $L$ is $L^* = \bigcup_{n \ge 0} L^n$, the [words](#def-b2-finite-automata-word) made by concatenating any number of [words](#def-b2-finite-automata-word) of $L$, none included.

For example, $\{a, b\}^*$ is every [word](#def-b2-finite-automata-word) over $\{a, b\}$, $\{ab\}^* = \{\varepsilon, ab, abab, \dots\}$, and $\{a\}\{b\}^*$, written $ab^*$, is the [words](#def-b2-finite-automata-word) made of one $a$ and then any number of $b$’s.

**Definition 21.3 (Prefix, suffix, factor, subword).**

Let $w = uxv$ with $u, x, v$ [words](#def-b2-finite-automata-word). Then $u$ is a *prefix* of $w$, $v$ a *suffix*, and $x$ a *factor*: a block of consecutive letters. A *subword* of $w$ is a [word](#def-b2-finite-automata-word) obtained by deleting letters of $w$, not necessarily consecutive.

The [word](#def-b2-finite-automata-word) $abca$ has the [prefixes](#def-b2-finite-automata-factor) $\varepsilon, a, ab, abc, abca$; $bc$ is a [factor](#def-b2-finite-automata-factor); $aa$ is a [subword](#def-b2-finite-automata-factor) but not a [factor](#def-b2-finite-automata-factor). A [word](#def-b2-finite-automata-word) of length $n$ has $n + 1$ [prefixes](#def-b2-finite-automata-factor) and $n + 1$ [suffixes](#def-b2-finite-automata-factor).

## 21.2 Deterministic automata

**Definition 21.4 (Deterministic finite automaton).**

A *deterministic finite automaton* (DFA) is $A = (Q, \Sigma, \delta, q_0,
F)$: a finite set of *states* $Q$, an [alphabet](#def-b2-finite-automata-word) $\Sigma$, a *transition function* $\delta$, a partial map from $Q \times \Sigma$ to $Q$, a start state $q_0$, and a set $F \subseteq Q$ of *accepting states*. The *extended* transition function $\delta^*$ on [words](#def-b2-finite-automata-word) is defined by $\delta^*(q, \varepsilon) = q$ and $\delta^*(q, wa) = \delta(\delta^*(q, w), a)$, undefined as soon as one step is. $A$ *accepts* $w$ when $\delta^*(q_0, w)$ is defined and lies in $F$, and the *[language](#def-b2-finite-automata-language) recognised* by $A$ is $L(A)$, the set of [words](#def-b2-finite-automata-word) it accepts.

![The automaton of the hook. A missing arrow is a missing transition: the string is rejected there. The accepting states have a double circle.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-finite-automata/fig-50388e9a9089.svg)

*The automaton of the hook. A missing arrow is a missing transition: the string is rejected there. The [accepting states](#def-b2-finite-automata-dfa) have a double circle.*

**Proposition 21.5 (Reading in two parts).**

For every state $q$ and [words](#def-b2-finite-automata-word) $u, v$: $\delta^*(q, uv) = \delta^*(\delta^*(q, u), v)$, both sides being defined or undefined together.

**Proof.** By induction on $|v|$. For $v = \varepsilon$ both sides are $\delta^*(q, u)$. If $v = wa$, then $\delta^*(q, uwa) =
\delta(\delta^*(q, uw), a) = \delta(\delta^*(\delta^*(q, u), w), a) = \delta^*(\delta^*(q, u), wa)$, by the definition, the hypothesis for $w$, and the definition again; each equality holds also when one side is undefined. ∎

This is what makes an automaton a streaming program: after reading $u$, the state $\delta^*(q_0, u)$ is all that is needed to continue, whatever $u$ was. The `run_from` method of `automaton.rs`, the library of this chapter’s listings, is $\delta^*$ written as a [fold](https://one-course.com/books/computer-science/4/en/chapter/9-functional-programming#def-b2-functional-programming-fold) over the letters.

**Definition 21.6 (Complete automaton).**

A DFA is *complete* if $\delta(q, a)$ is defined for every state $q$ and letter $a$. Any DFA is made complete, with the same [language](#def-b2-finite-automata-language), by adding a non-accepting *sink* state $s$ and sending every missing transition, and every letter from $s$, to $s$.

**Definition 21.7 (Accessible, co-accessible, trim).**

A state $q$ is *accessible* if $q = \delta^*(q_0, u)$ for some [word](#def-b2-finite-automata-word) $u$, and *co-accessible* if $\delta^*(q, v) \in F$ for some [word](#def-b2-finite-automata-word) $v$. An automaton is *trim* if all its states are both.

**Proposition 21.8 (Trimming).**

Removing from a DFA every state that is not both [accessible](#def-b2-finite-automata-trim) and [co-accessible](#def-b2-finite-automata-trim), with the transitions that touch it, leaves the recognised [language](#def-b2-finite-automata-language) unchanged. Both sets are computed by a graph search, in time linear in the number of transitions.

**Proof.** If $w$ is accepted, every state on its run is [accessible](#def-b2-finite-automata-trim) (by a [prefix](#def-b2-finite-automata-factor) of $w$) and [co-accessible](#def-b2-finite-automata-trim) (by the rest of $w$), so the run survives the removal. Conversely, removing states and transitions can only remove runs, so no new [word](#def-b2-finite-automata-word) is accepted. [Accessible states](#def-b2-finite-automata-trim) are those reachable from $q_0$ in the graph of the transitions; [co-accessible states](#def-b2-finite-automata-trim) are those from which $F$ is reachable, that is, those reachable from $F$ in the reversed graph. ∎

**Definition 21.9 (Recognisable language).**

A [language](#def-b2-finite-automata-language) is *recognisable* if some finite automaton recognises it.

## 21.3 Nondeterministic automata

Consider the [words](#def-b2-finite-automata-word) over $\{a, b\}$ whose third letter from the end is $a$. Reading from the left, a program cannot know which letter will be third from the end. It would be easy if it could *guess*: on each $a$, guess “this is the one”, then check that exactly two letters follow.

**Definition 21.10 (Nondeterministic finite automaton).**

A *nondeterministic finite automaton* (NFA) is $A = (Q, \Sigma, \Delta,
I, F)$ where $\Delta \subseteq Q \times \Sigma \times Q$ is a set of transitions, so that a state may have several transitions, or none, on the same letter, and $I \subseteq Q$ is a set of start states. A *run* on $w = a_1
\cdots a_n$ is a sequence $q_0 q_1 \cdots q_n$ with $q_0 \in I$ and $(q_{i-1}, a_i, q_i) \in \Delta$; $A$ *accepts* $w$ if *some* run on $w$ ends in $F$.

![Left: an NFA for “the third letter from the end is a”; state 0 has two transitions on a. Right: an NFA for a*b*c* with spontaneous transitions (dashed).](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-finite-automata/fig-1e57584d62e0.svg)

*Left: an NFA for “the third letter from the end is $a$”; state 0 has two transitions on $a$. Right: an NFA for $a^*b^*c^*$ with [spontaneous transitions](#def-b2-finite-automata-epsilon) (dashed).*

A nondeterministic automaton is not a program that guesses well; it is a definition by existence of a run. It is also convenient to allow moves that read nothing.

**Definition 21.11 (Spontaneous transition, closure).**

An NFA *with spontaneous transitions* also has a set of pairs $(p, q)$, written $p \xrightarrow{\varepsilon}
q$, which a run may take without reading a letter. The *$\varepsilon$-closure* of a set $S$ of states is the set of states reachable from $S$ by spontaneous transitions alone, $S$ included: the states reachable from $S$ in the graph of those transitions.

```rust
    /// The states reachable from the set by spontaneous transitions: a graph search.
    pub fn closure(&self, set: &Subset) -> Subset {
        let mut out = set.clone();
        let mut todo: Vec<usize> = set.iter().copied().collect();
        while let Some(q) = todo.pop() {
            for &r in &self.eps[q] {
                if out.insert(r) {
                    todo.push(r); // new: its own spontaneous moves follow
                }
            }
        }
        out
    }

    /// One letter from a closed set of states, then the closure.
    pub fn step(&self, set: &Subset, a: usize) -> Subset {
        let next = set.iter().flat_map(|&q| self.delta[q][a].iter().copied()).collect();
        self.closure(&next)
    }
```

***Listing 21.2.** The closure by a graph search, and one letter followed by the closure code/bachelor-2/21-finite-automata/listings/automaton.rs*

**Proposition 21.12 (Removing spontaneous transitions).**

Let $\mathrm{cl}(q)$ be the closure of $\{q\}$. The NFA with the same states and start states, the transitions $(q, a,
r)$ for every $r$ in the closure of $\{r' : (p, a, r') \in \Delta,\ p \in \mathrm{cl}(q)\}$, no [spontaneous transition](#def-b2-finite-automata-epsilon), and the [accepting states](#def-b2-finite-automata-dfa) $\{q : \mathrm{cl}(q) \cap F \ne \emptyset\}$, recognises the same [language](#def-b2-finite-automata-language).

**Proof.** A run of the original automaton on $a_1 \cdots a_n$ is a sequence of spontaneous moves, a letter, spontaneous moves, and so on. Cut it just before each letter: from state $q_{i-1}$ at the cut, it moves spontaneously within $\mathrm{cl}(q_{i-1})$, reads $a_i$, then moves spontaneously to the next cut $q_i$, which is exactly a new transition $(q_{i-1}, a_i, q_i)$; after the last letter it moves spontaneously to $F$, which makes $q_n$ accepting in the new automaton. Conversely, each new transition and each new [accepting state](#def-b2-finite-automata-dfa) unfolds into such moves of the original one. ∎

```
$ rustc --edition 2021 -O -o epsilon epsilon.rs && ./epsilon
closure of 0: {0, 1, 2}
closure of 1: {1, 2}
closure of 2: {2}
state 0: a -> [0, 1, 2], b -> [1, 2], c -> [2]  accepting
state 1: a -> [], b -> [1, 2], c -> [2]  accepting
state 2: a -> [], b -> [], c -> [2]  accepting
1093 of 1093 words up to length 6 judged alike; 84 accepted
```

***Output 21.2.** The closures of $a^*b^*c^*$’s states, the automaton without [spontaneous transitions](#def-b2-finite-automata-epsilon), and a check on every [word](#def-b2-finite-automata-word) up to length 6.*

## 21.4 The subset construction

An NFA can be run by a program that keeps the *set* of states it might be in. That set takes finitely many values, which makes it the state of a DFA.

**Method 21.13 (The subset construction).**

Given an NFA $(Q, \Sigma, \Delta, I, F)$, build a DFA whose states are sets of NFA states. The start state is $\mathrm{cl}(I)$. From a set $S$ and a letter $a$, the transition goes to $\mathrm{cl}(\{r : (p, a, r) \in \Delta,\
p \in S\})$. A set is accepting if it contains a state of $F$. Build only the sets reachable from the start, with a queue.

```rust
    /// The subset construction, from the start set, keeping accessible subsets only.
    pub fn determinise(&self) -> (Dfa, Vec<Subset>) {
        let first = self.closure(&self.start.iter().copied().collect());
        let mut index = HashMap::from([(first.clone(), 0)]);
        let (mut subsets, mut delta) = (vec![first], Vec::new());
        let mut todo = VecDeque::from([0]);
        while let Some(i) = todo.pop_front() {
            let mut row = Vec::new();
            for a in 0..self.alphabet.len() {
                let target = self.step(&subsets[i], a);
                let j = *index.entry(target.clone()).or_insert_with(|| {
                    subsets.push(target);
                    todo.push_back(subsets.len() - 1);
                    subsets.len() - 1
                });
                row.push(Some(j));
            }
            delta.push(row);
        }
        let accept = subsets.iter().map(|s| s.iter().any(|&q| self.accept[q])).collect();
        (Dfa { alphabet: self.alphabet.clone(), delta, start: 0, accept }, subsets)
    }
```

***Listing 21.3.** The [subset construction](#met-b2-finite-automata-subset): each new set gets a number and joins the queue code/bachelor-2/21-finite-automata/listings/automaton.rs*

**Theorem 21.14 (The subset construction is correct).**

For every [word](#def-b2-finite-automata-word) $w$, the state of the DFA after reading $w$ is the set of NFA states at which some run on $w$ can end. Hence the DFA recognises the [language](#def-b2-finite-automata-language) of the NFA, and a [language](#def-b2-finite-automata-language) is [recognisable](#def-b2-finite-automata-recognisable) by an NFA if and only if it is [recognisable](#def-b2-finite-automata-recognisable) by a DFA.

**Proof.** By induction on $|w|$. For $w = \varepsilon$, the runs on $\varepsilon$ are the spontaneous moves from $I$, which end exactly in $\mathrm{cl}(I)$, the start state. Suppose the claim holds for $w$, with set $S$. A run on $wa$ is a run on $w$, ending in some $p \in S$, then a transition $(p, a, r)$, then spontaneous moves: it ends exactly in the closure of the $r$’s, which is the transition of the DFA from $S$ on $a$. So the DFA’s state after $w$ contains a state of $F$ if and only if some run on $w$ ends in $F$. Conversely a DFA is an NFA with one start state and at most one transition per state and letter. ∎

```
$ rustc --edition 2021 -O -o subset subset.rs && ./subset
DFA state  subset of NFA states   on a       on b
        0  {0}                   {0,1}      {0}
        1  {0,1}                 {0,1,2}    {0,2}
        2  {0,1,2}               {0,1,2,3}  {0,2,3}
        3  {0,2}                 {0,1,3}    {0,3}
        4  {0,1,2,3}             {0,1,2,3}  {0,2,3}    accepting
        5  {0,2,3}               {0,1,3}    {0,3}      accepting
        6  {0,1,3}               {0,1,2}    {0,2}      accepting
        7  {0,3}                 {0,1}      {0}        accepting
abb    NFA true   DFA true
bab    NFA false  DFA false
baab   NFA true   DFA true
abba   NFA false  DFA false
```

***Output 21.3.** The determinisation of “the third letter from the end is $a$”: eight sets of states.*

The DFA remembers which of the last three letters were $a$: the set $\{0, 2, 3\}$ means the last letter was $b$ and the two before it were $a$. That needs $2^3$ states, and no DFA can do with fewer.

**Theorem 21.15 (The blow-up is unavoidable).**

Let $L_k$ be the [words](#def-b2-finite-automata-word) over $\{a, b\}$ whose $k$-th letter from the end is $a$. An NFA with $k + 1$ states recognises $L_k$, and every DFA that recognises $L_k$ has at least $2^k$ states; the [subset construction](#met-b2-finite-automata-subset) produces exactly $2^k$.

**Proof.** Let $u \ne v$ be two [words](#def-b2-finite-automata-word) of length $k$, and $i$ the first position, counting from 0, where they differ; say $u$ has $a$ there and $v$ has $b$. Append $b^i$: in $ub^i$ and $vb^i$, that position is now $k$-th from the end, so $ub^i
\in L_k$ and $vb^i \notin L_k$. In a DFA recognising $L_k$, if $\delta^*(q_0, u) = \delta^*(q_0, v)$ then by [Proposition 21.5](#prop-b2-finite-automata-extended) $\delta^*(q_0, ub^i) = \delta^*(q_0, vb^i)$, and the two [words](#def-b2-finite-automata-word) would be both accepted or both rejected. So the $2^k$ [words](#def-b2-finite-automata-word) of length $k$ lead to $2^k$ different states. The NFA of the figure has $k + 1$ states; the reachable sets of the [subset construction](#met-b2-finite-automata-subset) are $\{0\} \cup T$ for the $2^k$ sets $T \subseteq \{1,
\dots, k\}$ of positions among the last $k$ letters that hold an $a$, all reached. ∎

```
$ rustc --edition 2021 -O -o blowup blowup.rs && ./blowup
 k  NFA states  DFA states   2^k  reached by the 2^k words  pairs told apart
 1           2           2     2                         2                 1
 2           3           4     4                         4                 6
 3           4           8     8                         8                28
 4           5          16    16                        16               120
 5           6          32    32                        32               496
 6           7          64    64                        64              2016
 7           8         128   128                       128              8128
 8           9         256   256                       256             32640
 9          10         512   512                       512            130816
10          11        1024  1024                      1024            523776
11          12        2048  2048                      2048           2096128
12          13        4096  4096                      4096           8386560
```

***Output 21.4.** For $k = 1$ to 12, the states of both automata, and the proof’s argument checked on every pair of [words](#def-b2-finite-automata-word) of length $k$.*

A set of [words](#def-b2-finite-automata-word) that must lead to pairwise different states, as here, is a *fooling set*; it gives a lower bound on the size of every DFA for the [language](#def-b2-finite-automata-language) ([Exercise 21.10](#exo-b2-finite-automata-10)).

**History.**

Finite automata come from the 1950s. Stephen Kleene’s paper of 1956, in the collection *Automata Studies*, started from models of nerve nets and characterised the “events” a finite automaton can recognise; that result is the next chapter’s main theorem. In 1959 Michael Rabin and Dana Scott defined nondeterministic automata and proved that the [subset construction](#met-b2-finite-automata-subset) removes the nondeterminism, the theorem of this section.

## 21.5 Combining automata

**Definition 21.16 (Product automaton).**

The *product* of two [complete](#def-b2-finite-automata-complete) DFAs $(P, \Sigma, \delta, p_0, F)$ and $(Q, \Sigma,
\gamma, q_0, G)$ has the states $P \times Q$, the start $(p_0, q_0)$ and the transitions $(p, q) \xrightarrow{a}
(\delta(p, a), \gamma(q, a))$: it runs both automata at once.

**Proposition 21.17 (Closure under the Boolean operations).**

If $L$ and $M$ are [recognisable](#def-b2-finite-automata-recognisable), so are $\Sigma^* \setminus L$, $L \cup M$ and $L \cap M$.

**Proof.** Take [complete](#def-b2-finite-automata-complete) DFAs for $L$ and $M$. Swapping accepting and other states of the first gives the complement: the run on every [word](#def-b2-finite-automata-word) is defined and ends in exactly one state, accepting in one automaton if and only if not in the other. By induction on $|w|$, the [product](#def-b2-finite-automata-product)’s state after $w$ is the pair of the two states after $w$; so with [accepting states](#def-b2-finite-automata-dfa) $F
\times G$ it recognises $L \cap M$, and with $(F \times Q) \cup (P \times G)$ it recognises $L \cup M$. ∎

Completeness matters for the complement: an incomplete automaton rejects some [words](#def-b2-finite-automata-word) by having no run at all, and swapping its [accepting states](#def-b2-finite-automata-dfa) leaves them rejected ([Exercise 21.2](#exo-b2-finite-automata-2)). The [product](#def-b2-finite-automata-product) of “even length” and “starts with $a$” has six states, and not all of them are useful:

```
$ rustc --edition 2021 -O -o product product.rs && ./product
pair    on a    on b    accepting  accessible  co-accessible
(0,0)   (1,1)   (1,2)   false      true        true
(0,1)   (1,1)   (1,1)   true       true        true
(0,2)   (1,2)   (1,2)   false      true        false
(1,0)   (0,1)   (0,2)   false      false       true
(1,1)   (0,1)   (0,1)   false      true        true
(1,2)   (0,2)   (0,2)   false      true        false
trim automaton: 3 of 6 states
accepted words of length 0..8: [0, 0, 2, 0, 8, 0, 32, 0, 128]
```

***Output 21.5.** The [product](#def-b2-finite-automata-product) for the intersection, its useless states, and the number of accepted [words](#def-b2-finite-automata-word) of each length.*

![The product of “even length” (first component) and “starts with a” (0: start, 1: began with a, 2: began with b). Grey: (1, 0) is not accessible; (1, 2) and (0, 2) cannot reach the accepting state. The trim automaton keeps three states.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-finite-automata/fig-9620381109c6.svg)

*The [product](#def-b2-finite-automata-product) of “even length” (first component) and “starts with $a$” (0: start, 1: began with $a$, 2: began with $b$). Grey: $(1, 0)$ is not [accessible](#def-b2-finite-automata-trim); $(1, 2)$ and $(0, 2)$ cannot reach the [accepting state](#def-b2-finite-automata-dfa). The [trim automaton](#def-b2-finite-automata-trim) keeps three states.*

The counts, $2^{n-1}$ [words](#def-b2-finite-automata-word) of every even length $n \ge 2$, are computed from the automaton by dynamic programming: the number of [words](#def-b2-finite-automata-word) leading to each state, letter after letter ([Exercise 21.4](#exo-b2-finite-automata-4)).

## 21.6 Automata as programs

A DFA runs in constant time per letter: one table lookup, as in the hook. An NFA can be run either by building the DFA first, or by simulating it on the fly, keeping the set of possible states, which costs up to the number of NFA states per letter but builds nothing. With at most 64 states, the set fits in the bits of one machine word, and a step is a few shifts and ORs ([Exercise 21.11](#exo-b2-finite-automata-11)). On $L_k$, over two million letters:

```
$ rustc --edition 2021 -O -o simulate_vs_determinise simulate_vs_determinise.rs && ./simulate_vs_determinise
  k   NFA, sets    NFA, bits   DFA states   build (ms)          DFA
     ns/letter    ns/letter                             ns/letter
  4          100          5.3           16          0.0          3.9
 10          137          7.6         1024          0.7          7.8
 16          207          8.9        65536         79.8         82.5
```

***Output 21.6.** Simulating $L_k$’s NFA with sets as ordered trees or as bits, or building its DFA and running it, on the laptop.*

The DFA wins while it is small. At $k = 16$ it has 65 536 states, takes 80 ms to build, and runs slower than the simulation by bits, since its table no longer fits in the processor’s caches and each letter costs a memory access ([Chapter 12](https://one-course.com/books/computer-science/4/en/chapter/12-caches-and-the-memory-hierarchy#ch-b2-caches)). Programs that search text with patterns face the same choice, and many build the DFA lazily, one state the first time it is needed.

## 21.7 Exercises

**Exercise 21.1 ★.**

Give the run of the automaton of [Listing 21.1](#lst-b2-finite-automata-hook) on `0.0`, `-.5`, `1E+10`, `7e3.5` and `+`, and say which are accepted.

**Solution of Exercise 21.1.**

```
$ rustc --edition 2021 -O -o exo_runs exo_runs.rs && ./exo_runs
"0.0"    number states [0, 2, 3, 4]
"-.5"    no     states [0, 1]
"1E+10"  number states [0, 2, 5, 6, 7, 7]
"7e3.5"  no     states [0, 2, 5, 7]
"+"      no     states [0, 1]
```

***Output 21.7.** The five runs.*

`0.0` and `1E+10` are accepted. `-.5` stops in state 1: after a sign, only a digit may come. `7e3.5` stops in state 7: the exponent has no point. `+` ends in state 1, which is not accepting.

**Exercise 21.2 ★.**

The DFA with states 0 and 1, start 0, accepting 1, and the transitions $0 \xrightarrow{a} 1$ and $1 \xrightarrow{b}
1$ recognises $ab^*$. Swap its accepting and other states: which [language](#def-b2-finite-automata-language) do you get? Which [words](#def-b2-finite-automata-word) are missing from the complement, and how is it repaired?

**Solution of Exercise 21.2.**

```
$ rustc --edition 2021 -O -o exo_complement exo_complement.rs && ./exo_complement
word   a b*    swapped  complement
""     false   true     true
"a"    true    false    false
"b"    false   false    true
"ab"   true    false    false
"ba"   false   false    true
"abb"  true    false    false
"aab"  false   false    true
```

***Output 21.8.** The automaton, its swapped version and the true complement.*

The swapped automaton accepts only $\varepsilon$: every other [word](#def-b2-finite-automata-word) either ends in state 1, now rejecting, or has no run. The [words](#def-b2-finite-automata-word) without a run in $ab^*$’s automaton, such as $b$, $ba$ or $aab$, are rejected by both, though the complement must accept them. Completing first with a sink state, then swapping, gives the complement ([Proposition 21.17](#prop-b2-finite-automata-closure)).

**Exercise 21.3 ★.**

Build a DFA with three states that recognises the binary writings of the multiples of 3 (the [empty word](#def-b2-finite-automata-word) standing for 0), and prove it correct.

**Solution of Exercise 21.3.**

```
$ rustc --edition 2021 -O -o exo_mult3 exo_mult3.rs && ./exo_mult3
state 0: 0 -> 0, 1 -> 1  (start, accepting)
state 1: 0 -> 2, 1 -> 0
state 2: 0 -> 1, 1 -> 2
agrees with x % 3 == 0 for x = 0 .. 999: true
```

***Output 21.9.** The three states, and a check.*

The state is the value read so far, modulo 3: reading a bit $c$ after a [prefix](#def-b2-finite-automata-factor) of value $x$ gives the value $2x + c$, so state $r$ goes to $(2r + c) \bmod 3$. By induction on the length, $\delta^*(0, w) = \mathrm{val}(w) \bmod 3$: true for $\varepsilon$, of value 0, and kept by each step since $(2x + c) \bmod 3 = (2(x \bmod 3) + c) \bmod 3$. So $w$ is accepted, ending in state 0, exactly when its value is a multiple of 3.

**Exercise 21.4 ★.**

Build a [complete](#def-b2-finite-automata-complete) DFA for the [words](#def-b2-finite-automata-word) over $\{a, b\}$ that do not contain the [factor](#def-b2-finite-automata-factor) $bb$, and find a recurrence for the number $c_n$ of such [words](#def-b2-finite-automata-word) of length $n$.

**Solution of Exercise 21.4.**

```
$ rustc --edition 2021 -O -o exo_count exo_count.rs && ./exo_count
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
```

***Output 21.10.** $c_0$ to $c_{15}$, computed from the automaton.*

States: 0, the last letter is not $b$ (or no letter yet); 1, the last letter is $b$; 2, $bb$ has been seen, a sink. States 0 and 1 accept. Let $x_n$ and $y_n$ count the [words](#def-b2-finite-automata-word) of length $n$ ending in states 0 and 1. Then $x_{n+1} =
x_n + y_n$ (an $a$ from either) and $y_{n+1} = x_n$ (a $b$ from state 0 only), so $c_n = x_n + y_n$ satisfies $c_{n+1}
= x_{n+1} + y_{n+1} = c_n + x_n = c_n + c_{n-1}$, with $c_0 = 1$ and $c_1 = 2$: the Fibonacci numbers.

**Exercise 21.5 ★★.**

Apply the [subset construction](#met-b2-finite-automata-subset) to the NFA with states 0, 1, 2, start 0, accepting 2, and the transitions $0
\xrightarrow{a, b} 0$, $0 \xrightarrow{a} 1$ and $1 \xrightarrow{b} 2$. Which [language](#def-b2-finite-automata-language) is it?

**Solution of Exercise 21.5.**

```
$ rustc --edition 2021 -O -o exo_subset exo_subset.rs && ./exo_subset
0: {0}  a -> 1, b -> 0
1: {0, 1}  a -> 1, b -> 2
2: {0, 2}  a -> 1, b -> 0, accepting
```

***Output 21.11.** The three reachable sets.*

From $\{0\}$, $a$ leads to $\{0, 1\}$ and $b$ back to $\{0\}$; from $\{0, 1\}$, $a$ stays and $b$ leads to $\{0,
2\}$, accepting; from $\{0, 2\}$, $a$ leads to $\{0, 1\}$ and $b$ to $\{0\}$. Only 3 of the 8 subsets are reachable. The [language](#def-b2-finite-automata-language) is the [words](#def-b2-finite-automata-word) that end with $ab$.

**Exercise 21.6 ★★.**

A program computes the closure of a set by adding, once, the targets of the [spontaneous transitions](#def-b2-finite-automata-epsilon) of its states. On the automaton of $a^*b^*c^*$, which [words](#def-b2-finite-automata-word) does it get wrong, and why?

**Solution of Exercise 21.6.**

```
$ rustc --edition 2021 -O -o exo_closure_bug exo_closure_bug.rs && ./exo_closure_bug
""     one step: false  closure: true
"a"    one step: false  closure: true
"ab"   one step: true   closure: true
"abc"  one step: true   closure: true
"c"    one step: false  closure: true
```

***Output 21.12.** One spontaneous step against the closure.*

From $\{0\}$, one step adds 1 but not 2, which is two spontaneous steps away. So $\varepsilon$, $a$ and $c$ are wrongly rejected: each needs a run that passes from 0 to 2 without reading anything. [Words](#def-b2-finite-automata-word) that read a $b$ pass through state 1, from which one step reaches 2, and come out right. The closure is reachability in a graph, and must loop until no new state appears, as [Listing 21.2](#lst-b2-finite-automata-closure) does.

**Exercise 21.7 ★★.**

Build a DFA with four states for the [words](#def-b2-finite-automata-word) over $\{a, b\}$ that contain the [factor](#def-b2-finite-automata-factor) $aba$, and explain what each state remembers.

**Solution of Exercise 21.7.**

```rust
// factor_aba.rs: a DFA for the words over {a, b} that contain the factor aba (exercise 7).
// State i: the longest suffix of what was read that is a prefix of aba has length i;
// state 3: aba has been seen.
pub const DELTA: [[usize; 2]; 4] = [
    [1, 0], // "":  a starts the pattern, b does not
    [1, 2], // "a": a again keeps "a", b makes "ab"
    [3, 0], // "ab": a completes aba, b leaves nothing
    [3, 3], // found: stay
];

pub fn contains_aba(word: &str) -> bool {
    let mut q = 0;
    for c in word.chars() {
        q = DELTA[q][if c == 'a' { 0 } else { 1 }];
    }
    q == 3
}
```

*Searching for $aba$ code/bachelor-2/21-finite-automata/exercises/factor_aba.rs*

State $i \le 2$ means that the longest [suffix](#def-b2-finite-automata-factor) of what has been read that is a [prefix](#def-b2-finite-automata-factor) of $aba$ has length $i$; state 3 means $aba$ has appeared. From state 2 ($ab$), a $b$ gives $abb$, whose [suffixes](#def-b2-finite-automata-factor) $bb$, $b$, $\varepsilon$ are not [prefixes](#def-b2-finite-automata-factor) of $aba$ except $\varepsilon$: back to 0. From state 1 ($a$), an $a$ gives $aa$, whose longest such [suffix](#def-b2-finite-automata-factor) is $a$: state 1. The test compares it with `contains("aba")` on every [word](#def-b2-finite-automata-word) up to length 10. The same idea, for any pattern, is the automaton of the text-search algorithms of [Chapter 25](https://one-course.com/books/computer-science/4/en/chapter/25-text-algorithms-and-compression#ch-b2-text-algorithms).

**Exercise 21.8 ★★.**

The *reverse* of $w = a_1 \cdots a_n$ is $a_n \cdots a_1$. Show that if $L$ is [recognisable](#def-b2-finite-automata-recognisable), the set of the reverses of its [words](#def-b2-finite-automata-word) is [recognisable](#def-b2-finite-automata-recognisable).

**Solution of Exercise 21.8.**

Take a DFA for $L$ and reverse every transition: $(p, a, q)$ becomes $(q, a, p)$. Make the [accepting states](#def-b2-finite-automata-dfa) the start states, and the old start state the only [accepting state](#def-b2-finite-automata-dfa). This is an NFA; a run of it on $a_n \cdots a_1$ from some $q_n \in F$ to $q_0$ is exactly a run of the DFA on $a_1 \cdots a_n$ read backwards. So the NFA recognises the reverses of the [words](#def-b2-finite-automata-word) of $L$, and by [Theorem 21.14](#thm-b2-finite-automata-subset-correct) so does a DFA.

**Exercise 21.9 ★★.**

For integers $n \ge 1$ and $b \ge 2$, build a DFA with $n$ states that recognises the writings in base $b$ of the multiples of $n$, and test it.

**Solution of Exercise 21.9.**

```rust
// multiples.rs: the multiples of n written in base b, as a DFA on the digits (exercise 9).
// The state is the value read so far, modulo n: reading digit d sends r to (b r + d) mod n.

pub fn delta(n: u32, b: u32) -> Vec<Vec<u32>> {
    (0..n).map(|r| (0..b).map(|d| (b * r + d) % n).collect()).collect()
}

/// digits: most significant first; the empty word stands for 0.
pub fn is_multiple(n: u32, b: u32, digits: &[u32]) -> bool {
    let table = delta(n, b);
    digits.iter().fold(0, |r, &d| table[r as usize][d as usize]) == 0
}
```

*The multiples of $n$ in base $b$ code/bachelor-2/21-finite-automata/exercises/multiples.rs*

As in [Exercise 21.3](#exo-b2-finite-automata-3): reading a digit $d$ after a value $x$ gives $bx + d$, so the state $x \bmod n$ goes to $(b\,(x \bmod n) + d) \bmod n$; the start and the only [accepting state](#def-b2-finite-automata-dfa) are 0. The test checks five pairs $(n, b)$, $n = 1$ included, on every number below 2000.

**Exercise 21.10 ★★★.**

A *fooling set* for $L$ is a set $S$ of [words](#def-b2-finite-automata-word) such that for any two $u \ne v$ in $S$ there is a [word](#def-b2-finite-automata-word) $z$ with exactly one of $uz$ and $vz$ in $L$. Show that every [complete](#def-b2-finite-automata-complete) DFA recognising $L$ (one whose [transition function](#def-b2-finite-automata-dfa) is defined everywhere) has at least $|S|$ [accessible states](#def-b2-finite-automata-trim), and a partial one at least $|S| - 1$. Find a fooling set of size 3 for the [language](#def-b2-finite-automata-language) of [Exercise 21.3](#exo-b2-finite-automata-3).

**Solution of Exercise 21.10.**

Let $u \ne v$ in $S$, and suppose a DFA $A$ for $L$ has $\delta^*(q_0, u) = \delta^*(q_0, v)$, both defined. For the [word](#def-b2-finite-automata-word) $z$ that tells them apart, [Proposition 21.5](#prop-b2-finite-automata-extended) gives $\delta^*(q_0, uz) = \delta^*(q_0,
vz)$, so $uz$ and $vz$ are both accepted or both rejected: a contradiction. If one of the two runs is undefined, $u$ or $v$ has no extension in $L$, and at most one [word](#def-b2-finite-automata-word) of $S$ can be like that (two such [words](#def-b2-finite-automata-word) could not be told apart). So the [words](#def-b2-finite-automata-word) of $S$ lead to $|S|$ different states, or $|S| - 1$ states and one undefined run; the completed automaton has at least $|S|$ states, and the bound holds for every [complete](#def-b2-finite-automata-complete) DFA. For the multiples of 3, $S = \{\varepsilon, 1, 10\}$, of values 0, 1 and 2: appending $\varepsilon$ separates $\varepsilon$ from the others, and appending $1$ separates $1$ (value 3, a multiple) from $10$ (value 5).

**Exercise 21.11 ★★★.**

Write an NFA simulation that keeps the set of states as the bits of a 64-bit word, and compare its speed with the determinised automaton for $L_k$.

**Solution of Exercise 21.11.**

```rust
/// Simulation with the set of states as the bits of one machine word.
fn simulate_bits(n: &Nfa, word: &[usize]) -> bool {
    let mut masks = vec![[0u64; 2]; n.delta.len()]; // successors of q on a and on b
    for (q, row) in n.delta.iter().enumerate() {
        for a in 0..2 {
            masks[q][a] = row[a].iter().fold(0, |m, &r| m | 1 << r);
        }
    }
    let mut set = 1u64 << n.start[0];
    for &a in word {
        let mut next = 0;
        let mut rest = set;
        while rest != 0 {
            let q = rest.trailing_zeros() as usize; // one state of the set
            next |= masks[q][a];
            rest &= rest - 1;
        }
        set = next;
    }
    (0..n.delta.len()).any(|q| set >> q & 1 == 1 && n.accept[q])
}
```

*Simulation with the set of states as bits code/bachelor-2/21-finite-automata/listings/simulate_vs_determinise.rs*

For each state and letter, the set of successors is precomputed as a mask. A step ORs the masks of the states in the current set, found by `trailing_zeros` and cleared one by one. [Output 21.6](#out-b2-finite-automata-measured) gives about 5 to 9 ns per letter, against 100 to 210 with ordered sets, and against a DFA that wins for small $k$ but whose 65 536 states at $k = 16$ make each lookup a cache miss.

**Exercise 21.12 ★★★.**

Show that if $L$ is [recognisable](#def-b2-finite-automata-recognisable), the set of the [prefixes](#def-b2-finite-automata-factor) of its [words](#def-b2-finite-automata-word) is [recognisable](#def-b2-finite-automata-recognisable).

**Solution of Exercise 21.12.**

Take a [trim](#def-b2-finite-automata-trim) DFA for $L$ ([Proposition 21.8](#prop-b2-finite-automata-trim)), and make every state accepting. If $u$ is a [prefix](#def-b2-finite-automata-factor) of a [word](#def-b2-finite-automata-word) $uv \in L$, the run on $uv$ exists, so the run on $u$ exists and ends in a state of the [trim automaton](#def-b2-finite-automata-trim): accepted. Conversely, if the run on $u$ ends in a state $q$, then $q$ is [co-accessible](#def-b2-finite-automata-trim), so some $v$ leads from $q$ to an [accepting state](#def-b2-finite-automata-dfa), and $uv \in L$. If $L$ is empty, the [trim automaton](#def-b2-finite-automata-trim) has no state, and the [language](#def-b2-finite-automata-language) of [prefixes](#def-b2-finite-automata-factor) is empty too.

## 21.8 Problem: Decoding the lighthouse’s light signals

**Problem 21.1.**

Weekend problem — Decoding the lighthouse’s light signals

The lighthouse sends messages as flashes, short ($s$) or long ($l$). A message is a [word](#def-b2-finite-automata-word) over $\{s, l\}$; the harbour reads it as it comes.

**Part I — Signals as words.**

1. How many messages of length 10 are there, and how many of length at most 10?
2. List the [prefixes](#def-b2-finite-automata-factor) , [suffixes](#def-b2-finite-automata-factor) and [factors](#def-b2-finite-automata-factor) of length 2 of $sllsl$ .
3. Is $ss$ a [subword](#def-b2-finite-automata-factor) of $slsl$ ? A [factor](#def-b2-finite-automata-factor) ?
4. Describe $\{s, l\}^* l \{s, l\}^*$ and $\{ss, l\}^*$ in [words](#def-b2-finite-automata-word) .
5. Show that $L^* L^* = L^*$ for every [language](#def-b2-finite-automata-language) $L$ .
6. Is $\{s\}^* \{l\}^* = \{s, l\}^*$ ? Give a [word](#def-b2-finite-automata-word) that tells.

**Part II — Valid messages.**

A message is *valid* if it has an even number of long flashes and never three short flashes in a row.

7. Build a [complete](#def-b2-finite-automata-complete) DFA $P$ with two states for “an even number of $l$ ”.
8. Build a [complete](#def-b2-finite-automata-complete) DFA $N$ with four states for “no [factor](#def-b2-finite-automata-factor) $sss$ ”.
9. How many states has their [product](#def-b2-finite-automata-product) , and which are accepting?
10. Which states of the [product](#def-b2-finite-automata-product) are not [co-accessible](#def-b2-finite-automata-trim) ? How many states does the [trim automaton](#def-b2-finite-automata-trim) keep?
11. Run it on $slslss$ and $lssslsl$ .
12. Write the recurrence that counts valid messages, state by state, and compute the counts for lengths 0 to 6.

**Part III — A pattern near the end.**

The harbour must react when the fourth flash from the end is long.

13. Draw an NFA with 5 states for it.
14. What does its [subset construction](#met-b2-finite-automata-subset) remember after each flash?
15. How many states does the DFA have, and what is its start state?
16. Give two messages of length 4 that lead to different DFA states, and a [suffix](#def-b2-finite-automata-factor) that tells them apart.
17. Is the NFA’s on-the-fly simulation cheaper than the DFA here? Use [Output 21.6](#out-b2-finite-automata-measured) .
18. Why can the harbour not use an automaton that reads the message backwards?

**Part IV — The blow-up.**

19. For “the $k$ -th flash from the end is long”, how many states do the NFA and the DFA need?
20. Which $2^k$ [words](#def-b2-finite-automata-word) form a fooling set, and why does that prove the bound?
21. Could a different NFA with fewer than $k + 1$ states recognise the [language](#def-b2-finite-automata-language) ?
22. To check also that the message is valid, the harbour runs the [product](#def-b2-finite-automata-product) of the DFA of question 19 with the [trim automaton](#def-b2-finite-automata-trim) of question 10. At most how many states does it have for $k = 4$ ?
23. How does [Output 21.4](#out-b2-finite-automata-blowup) check the proof for $k \le 12$ ?
24. State the result: the $2^k$ law, exactly $2^k$ states, none removable.

**Solution of Problem 21.1.**

**1.** $2^{10} = 1024$; $2^{11} - 1 = 2047$ of length at most 10.

**2.** [Prefix](#def-b2-finite-automata-factor) $sl$, [suffix](#def-b2-finite-automata-factor) $sl$; [factors](#def-b2-finite-automata-factor) of length 2: $sl$, $ll$, $ls$.

**3.** $ss$ is a [subword](#def-b2-finite-automata-factor) (delete both $l$’s) but not a [factor](#def-b2-finite-automata-factor).

**4.** The messages that contain at least one long flash; the messages in which short flashes come in pairs (every maximal block of $s$ has even length).

**5.** $L^* \subseteq L^* L^*$ since $\varepsilon \in L^*$; and a concatenation of $i$ [words](#def-b2-finite-automata-word) of $L$ followed by $j$ [words](#def-b2-finite-automata-word) of $L$ is a concatenation of $i + j$ of them.

**6.** No: $ls$ is in $\{s, l\}^*$ but not in $s^* l^*$.

**7.** States $E$ (even, start, accepting) and $O$; $l$ swaps them, $s$ keeps them.

**8.** States 0, 1, 2 (the number of trailing $s$, all accepting) and a sink 3: $s$ moves $i$ to $i + 1$ (2 to 3), $l$ moves 0, 1, 2 to 0.

**9.** 8 states; accepting: $(E, 0)$, $(E, 1)$, $(E, 2)$.

**10.** $(E, 3)$ and $(O, 3)$, the sink pairs, cannot reach acceptance; all states are [accessible](#def-b2-finite-automata-trim) (from the start, $sss$ and $lsss$ reach the two sink pairs). The [trim automaton](#def-b2-finite-automata-trim) keeps 6 states.

**11.** $slslss$: $(E,0) \to (E,1) \to (O,0) \to (O,1) \to (E,0) \to (E,1) \to (E,2)$, accepted. $lssslsl$: after $lsss$ the run is in $(O, 3)$, rejected.

**12.** Writing $e_i(n)$ and $o_i(n)$ for the [words](#def-b2-finite-automata-word) of length $n$ ending in $(E, i)$ and $(O, i)$: $e_0(n+1) = o_0(n) + o_1(n) + o_2(n)$ and $o_0(n+1) = e_0(n) + e_1(n) + e_2(n)$ (an $l$ switches the parity), and $e_{i+1}(n+1) = e_i(n)$, $o_{i+1}(n+1) = o_i(n)$ for $i = 0, 1$. The valid messages of lengths 0 to 6 are 1, 1, 2, 3, 7, 12, 22.

**13.** States 0 to 4: 0 loops on $s$ and $l$, $0 \xrightarrow{l} 1$, then $i \xrightarrow{s, l} i + 1$ up to 4, accepting.

**14.** Which of the last four flashes were long: the set $\{0\} \cup T$, where $T$ holds the positions, among the last four, of the long ones.

**15.** $2^4 = 16$ states; the start state is $\{0\}$.

**16.** $lsss$ and $ssss$: the [suffix](#def-b2-finite-automata-factor) $\varepsilon$ tells them apart, since the first has a long flash fourth from the end.

**17.** For $k = 4$, the DFA has 16 states and its table fits in the caches: in [Output 21.6](#out-b2-finite-automata-measured) it runs at about 4 ns a flash, a little faster than the simulation by bits. The simulation wins only for large $k$.

**18.** The flashes arrive one at a time and the harbour must react as they come; a backward automaton would need the whole message first. (Read backwards, the condition concerns the fourth flash from the start, which a 5-state DFA checks.)

**19.** $k + 1$ for the NFA, $2^k$ for the DFA ([Theorem 21.15](#thm-b2-finite-automata-blowup)).

**20.** The $2^k$ messages of length $k$: any two differ first at some position $i$, and the [suffix](#def-b2-finite-automata-factor) $s^i$ puts that flash $k$-th from the end, so one message becomes accepted and the other not; by [Exercise 21.10](#exo-b2-finite-automata-10), every DFA has at least $2^k$ states.

**21.** No. Take the pairs $x_i = l^i$, $y_i = l^{k-i}$ for $i = 0, \dots, k$: $x_i y_i = l^k$ is accepted, so an accepting run passes, after $x_i$, through some state $q_i$. If $q_i = q_j$ with $i < j$, the run on $x_i$ followed by the rest of the run on $y_j$ accepts $l^{i + k - j}$, which has fewer than $k$ letters and is not in the [language](#def-b2-finite-automata-language). So the $k + 1$ states $q_i$ are distinct.

**22.** At most $16 \times 6 = 96$ pairs, of which only the [accessible](#def-b2-finite-automata-trim) ones need to be built.

**23.** It counts the states reached by the $2^k$ [words](#def-b2-finite-automata-word) of length $k$, and checks, for each of the pairs, that the [suffix](#def-b2-finite-automata-factor) of the proof makes exactly one of the two [words](#def-b2-finite-automata-word) accepted: 8 386 560 pairs for $k = 12$.

**24.** The $2^k$ law: for “the $k$-th letter from the end”, an NFA has $k + 1$ states, and every DFA has at least $2^k$, which the [subset construction](#met-b2-finite-automata-subset) reaches exactly; none of its states can be removed or merged, since the [words](#def-b2-finite-automata-word) of length $k$ lead to pairwise distinguishable states.
