---
title: "Regular Expressions and the Limits of Regular Languages"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 22
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/22-regular-expressions-and-the-limits-of-regular-languages
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 22 — Regular Expressions and the Limits of Regular Languages

A search box accepts a pattern: `(a|a)*b` asks for some $a$’s, each written in one of two ways, then a $b$. On a text of $a$’s with no $b$, Python’s pattern engine answers “no match”. The program times that answer:

```python
"""backtracking.py: Python's re on (a|a)*b against a^n, which has no b: time per n."""
import subprocess
import sys

PROGRAM = """
import re, time
pattern, text = re.compile("(a|a)*b"), "a" * {n}
t = time.perf_counter()
assert pattern.match(text) is None             # every way of splitting is tried
print(time.perf_counter() - t)
"""

print("   n   time (s)   ratio to n - 1")
previous = None
for n in range(16, 28):
    try:                                         # each run in its own process, bounded
        run = subprocess.run([sys.executable, "-c", PROGRAM.format(n=n)],
                             capture_output=True, text=True, timeout=60)
        seconds = float(run.stdout)
    except subprocess.TimeoutExpired:
        print(f"{n:4}   over 60 s: stopped")
        break
    ratio = f"{seconds / previous:6.2f}" if previous else ""
    print(f"{n:4} {seconds:10.4f}   {ratio}".rstrip())
    previous = seconds
```

***Listing 22.1.** Timing one pattern on longer and longer texts, each run in its own bounded [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) code/bachelor-2/22-regular-languages/listings/backtracking.py*

```
$ python backtracking.py
   n   time (s)   ratio to n - 1
  16     0.0033
  17     0.0067     2.01
  18     0.0130     1.96
  19     0.0255     1.96
  20     0.0574     2.25
  21     0.1125     1.96
  22     0.2097     1.86
  23     0.4259     2.03
  24     0.8915     2.09
  25     1.7003     1.91
  26     3.5214     2.07
  27     6.6253     1.88
```

***Output 22.1.** Python’s `re` on `(a|a)*b` and $a^n$, on the laptop.*

Each extra $a$ doubles the time: 27 letters take more than six seconds, and a search box that receives such a pattern freezes. The pattern is not hard. It means the same as `a*b`, and the previous chapter’s automata decide it in one step per letter. This chapter connects the two: patterns, called [regular expressions](#def-b2-regular-languages-regex), describe exactly the languages that finite automata recognise; every automaton has a smallest equivalent one, which is unique; and some simple languages, such as balanced brackets, are beyond both. It ends with a pattern engine that cannot freeze.

**You already know.**

[Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata): words, languages, concatenation $LM$ and star $L^*$; deterministic automata (DFA), complete and trim; nondeterministic automata (NFA) with [spontaneous transitions](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-epsilon), which the [subset construction](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#met-b2-finite-automata-subset) turns into DFAs, at a cost of up to $2^k$ states; the [product automaton](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-product), so that [recognisable languages](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-recognisable) are closed under union, intersection and complement. The Year 1 volume: structural induction on trees, proving a property for leaves and then for each node from its children.

## 22.1 Regular expressions

**Definition 22.1 (Regular expression, denoted language).**

The *regular expressions* over an [alphabet](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) $\Sigma$ are the trees built by these rules: $\emptyset$ and $\varepsilon$ are expressions, every letter $a \in \Sigma$ is an expression, and if $e$ and $f$ are expressions, so are $e \mid f$ (alternation), $ef$ (concatenation) and $e^*$ (star). The *language denoted* by an expression is defined on the tree: $L(\emptyset) = \emptyset$, $L(\varepsilon)
= \{\varepsilon\}$, $L(a) = \{a\}$, $L(e \mid f) = L(e) \cup L(f)$, $L(ef) = L(e) L(f)$ and $L(e^*) = L(e)^*$. Two expressions are *equivalent* if they denote the same language.

Written on one line, star binds tighter than concatenation, which binds tighter than alternation: $ab^* \mid c$ is $(a(b^*)) \mid c$. The *size* of an expression is the number of nodes of its tree. So $(a \mid b)^*abb$ denotes the words over $\{a, b\}$ that end with $abb$, and $(ab \mid b)^*$ the words in which every $a$ is followed by a $b$. The library of this chapter’s listings, `regex.rs`, holds the tree as a Rust enumeration with six cases, and its function `lang` is the definition run, cut at a length $n$ so that the sets stay finite:

```rust
/// The denotation, cut to the words of length at most n: the definition, run.
pub fn lang(re: &Re, n: usize) -> BTreeSet<String> {
    match re {
        Re::Empty => BTreeSet::new(),
        Re::Eps => BTreeSet::from([String::new()]),
        Re::Char(c) => if n >= 1 { BTreeSet::from([c.to_string()]) } else { BTreeSet::new() },
        Re::Alt(x, y) => lang(x, n).union(&lang(y, n)).cloned().collect(),
        Re::Cat(x, y) => {
            let (lx, ly) = (lang(x, n), lang(y, n));
            lx.iter().flat_map(|u| ly.iter().filter(move |v| u.len() + v.len() <= n)
                .map(move |v| format!("{u}{v}"))).collect()
        }
        Re::Star(x) => {
            let lx = lang(x, n);
            let mut all = BTreeSet::from([String::new()]);
            let mut frontier = all.clone();
            while !frontier.is_empty() { // add one more factor until nothing new fits
                let next: BTreeSet<String> = frontier.iter()
                    .flat_map(|u| lx.iter().filter(move |v| u.len() + v.len() <= n)
                        .map(move |v| format!("{u}{v}")))
                    .filter(|w| !all.contains(w)).collect();
                all.extend(next.iter().cloned());
                frontier = next;
            }
            all
        }
    }
}
```

***Listing 22.2.** The denotation, by induction on the tree; the star adds one more factor until nothing new fits code/bachelor-2/22-regular-languages/listings/regex.rs*

It is slow, since it builds every word, but it is obviously right, and the tests check the fast code against it.

**Definition 22.2 (Regular language).**

A language is *regular* if some [regular expression](#def-b2-regular-languages-regex) denotes it. Equivalently, the regular languages form the smallest class of languages that contains $\emptyset$, $\{\varepsilon\}$ and every $\{a\}$, and is closed under union, concatenation and star.

The two descriptions agree by structural induction: every [denoted language](#def-b2-regular-languages-regex) is in any such class, and the [denoted languages](#def-b2-regular-languages-regex) form such a class. Every finite language is [regular](#def-b2-regular-languages-regular): $\{w_1, \dots, w_k\}$ is denoted by $w_1 \mid \cdots
\mid w_k$.

**Definition 22.3 (Extended regular expression).**

An *extended regular expression* also uses these abbreviations: a class `[abc]` for $a \mid b \mid c$ and a range `[a-z]` for every letter from `a` to `z`; $e^+$ for $ee^*$; $e?$ for $e \mid \varepsilon$; and the counts $e\{m,n\}$ for $m$ copies of $e$ followed by $n - m$ copies of $e?$, with $e\{m\} = e\{m,m\}$.

Each abbreviation is an ordinary expression, so extended expressions denote [regular languages](#def-b2-regular-languages-regular) too; but they can be much shorter: $(a \mid b)\{20\}$ stands for an expression with 40 letters. The parser of `regex.rs` reads them by recursive descent, one function per priority level; the function for the postfix operators expands them on the spot:

```rust
fn parse_post(s: &[char], pos: &mut usize) -> Result<Re, String> {
    let mut re = parse_atom(s, pos)?;
    while *pos < s.len() {
        re = match s[*pos] {
            '*' => Re::Star(Box::new(re)),
            '+' => Re::Cat(Box::new(re.clone()), Box::new(Re::Star(Box::new(re)))), // xx*
            '?' => Re::Alt(Box::new(re), Box::new(Re::Eps)), // x|ε
            '{' => {
                let close = s[*pos..].iter().position(|&c| c == '}').ok_or("no '}'")? + *pos;
                let body: String = s[*pos + 1..close].iter().collect();
                let (m, n) = match body.split_once(',') {
                    Some((m, n)) => (m.parse(), n.parse()),
                    None => (body.parse(), body.parse()),
                };
                let bad = |_| "bad count";
                let (m, n): (usize, usize) = (m.map_err(bad)?, n.map_err(bad)?);
                *pos = close;
                repeat(&re, m, n) // m copies, then n - m optional ones
            }
            _ => break,
        };
        *pos += 1;
    }
    Ok(re)
}
```

***Listing 22.3.** Postfix operators: star, plus, option and counts, each rewritten into the basic syntax code/bachelor-2/22-regular-languages/listings/regex.rs*

The syntax here is a small one. Practical pattern languages add a wildcard for any character, anchors for the start and end of a line, and often *back-references*, which ask a later part of the text to repeat what an earlier group matched. Back-references go beyond [regular languages](#def-b2-regular-languages-regular) ([Section 22.4](#sec-22-4)); the other additions do not.

## 22.2 Kleene’s theorem

Expressions describe languages; automata recognise them. This section turns each into the other.

**Method 22.4 (Thompson’s construction).**

For each node of the expression’s tree, build an NFA *fragment* with [spontaneous transitions](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-epsilon), one entry state $i$ and one exit state $o$, no transition into $i$ and none out of $o$, by induction on the tree as drawn below:

- for $\emptyset$ : two states and no transition; for $\varepsilon$ : $i \xrightarrow{\varepsilon} o$ ; for a letter: $i \xrightarrow{a} o$ ;
- for $ef$ : $i$ to the entry of $e$ , the exit of $e$ to the entry of $f$ , the exit of $f$ to $o$ , all spontaneous;
- for $e \mid f$ : spontaneous moves from $i$ to both entries and from both exits to $o$ ;
- for $e^*$ : spontaneous moves from $i$ to the entry of $e$ and to $o$ , and from the exit of $e$ back to its entry and to $o$ .

The fragment of the whole expression, with $i$ as start and $o$ as only [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa), recognises $L(e)$. It has two states per node, $2s$ for an expression of size $s$, and at most two transitions leave each state.

![Thompson’s fragments. A box is the fragment of a subexpression, entered on its left and left on its right; every arrow but the letter’s is a spontaneous transition.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-regular-languages/fig-d55698235cac.svg)

*Thompson’s fragments. A box is the fragment of a subexpression, entered on its left and left on its right; every arrow but the letter’s is a [spontaneous transition](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-epsilon).*

Correctness is a structural induction: a path from $i$ to $o$ reads exactly a word of the subexpression’s language, since the only way out of a fragment is through its exit, which no transition leaves inside it. Thompson’s automaton is easy to build but full of spontaneous moves. Glushkov’s has none, and only one state per letter.

**Definition 22.5 (Linear expression, local language).**

An expression is *linear* if each letter occurs in it at most once. A language $L$ is *local* if there are sets $P, S \subseteq \Sigma$ and $F \subseteq \Sigma^2$ such that $L \setminus \{\varepsilon\}$ is the set of nonempty words whose first letter is in $P$, whose last letter is in $S$, and whose factors of length 2 are all in $F$.

Whether a word belongs to a [local language](#def-b2-regular-languages-local) is decided by a window of two letters slid along it. Any expression is made [linear](#def-b2-regular-languages-local) by numbering its letters from the left, its *positions*: $(a \mid b)^*abb$ becomes $(a_1 \mid b_2)^* a_3
b_4 b_5$. Erasing the numbers maps the [linear](#def-b2-regular-languages-local) expression’s language onto the original one.

**Definition 22.6 (Glushkov automaton).**

Let $e$ have positions $1, \dots, m$, the letter at position $j$ being $\ell(j)$, and let $e'$ be the [linear](#def-b2-regular-languages-local) expression. Define $\mathrm{Null}$ (whether $\varepsilon \in L(e)$), $\mathrm{First}$ (the positions that can begin a word of $L(e')$), $\mathrm{Last}$ (those that can end one), and $\mathrm{Follow}(j)$ (the positions that can come right after $j$ in a word of $L(e')$). The *Glushkov automaton* of $e$ has states $0, 1,
\dots, m$, start state 0, transitions $0 \xrightarrow{\ell(j)} j$ for $j \in \mathrm{First}$ and $i \xrightarrow{\ell(j)}
j$ for $j \in \mathrm{Follow}(i)$, and [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $\mathrm{Last}$, plus 0 if $\mathrm{Null}$.

**Method 22.7 (The Berry–Sethi computation).**

Compute $\mathrm{Null}$, $\mathrm{First}$ and $\mathrm{Last}$ for every subexpression, bottom up: a position $j$ has $(\mathrm{false}, \{j\}, \{j\})$; for $\varepsilon$, $(\mathrm{true}, \emptyset, \emptyset)$; an alternation takes the *or* and the unions; a concatenation $fg$ has $\mathrm{Null} = \mathrm{Null}(f) \wedge \mathrm{Null}(g)$, $\mathrm{First} = \mathrm{First}(f)$, joined by $\mathrm{First}(g)$ if $f$ is nullable, and symmetrically for $\mathrm{Last}$; a star is nullable with its body’s sets. On the way, at each concatenation $fg$ add $\mathrm{First}(g)$ to $\mathrm{Follow}(j)$ for every $j \in \mathrm{Last}(f)$, and at each star $f^*$ add $\mathrm{First}(f)$ to $\mathrm{Follow}(j)$ for every $j \in \mathrm{Last}(f)$.

The walk of `regex.rs` is this method, one case per kind of node:

```rust
/// Berry and Sethi: nullable, first and last of each subexpression, bottom up,
/// adding to follow at each concatenation and each star.
fn walk(re: &Re, g: &mut Glushkov) -> Sets {
    let none = BTreeSet::new;
    match re {
        Re::Empty => (false, none(), none()),
        Re::Eps => (true, none(), none()),
        Re::Char(c) => {
            g.letters.push(*c);
            g.follow.push(none());
            let j = g.letters.len(); // the next position
            (false, BTreeSet::from([j]), BTreeSet::from([j]))
        }
        Re::Alt(x, y) => {
            let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
            (nx || ny, &fx | &fy, &lx | &ly)
        }
        Re::Cat(x, y) => {
            let ((nx, fx, lx), (ny, fy, ly)) = (walk(x, g), walk(y, g));
            for &j in &lx {
                g.follow[j].extend(fy.iter()); // the end of x, then the start of y
            }
            let first = if nx { &fx | &fy } else { fx };
            let last = if ny { &lx | &ly } else { ly };
            (nx && ny, first, last)
        }
        Re::Star(x) => {
            let (_, fx, lx) = walk(x, g);
            for &j in &lx {
                g.follow[j].extend(fx.iter()); // the end of x, then x again
            }
            (true, fx, lx)
        }
    }
}
```

***Listing 22.4.** The Berry–Sethi computation: three values per subexpression, and the follow sets filled at each concatenation and each star code/bachelor-2/22-regular-languages/listings/regex.rs*

```
$ rustc --edition 2021 -O -o glushkov glushkov.rs && ./glushkov
positions: a1 b2 a3 b4 b5   nullable: false
first: {1, 2, 3}   last: {5}
follow(1) = {1, 2, 3}
follow(2) = {1, 2, 3}
follow(3) = {4}
follow(4) = {5}
follow(5) = {}
511 of 511 words up to length 8 judged as the definition says
```

***Output 22.2.** The positions and sets of $(a \mid b)^*abb$, and the automaton checked against the denotation.*

![The Glushkov automaton of (a b)*abb: one state per position, and every transition into a position carries that position’s letter. It is nondeterministic: from 0, a_1 and a_3 both read a.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-regular-languages/fig-ebca46117b4a.svg)

*The [Glushkov automaton](#def-b2-regular-languages-glushkov) of $(a \mid b)^*abb$: one state per position, and every transition into a position carries that position’s letter. It is nondeterministic: from 0, $a_1$ and $a_3$ both read $a$.*

**Proposition 22.8 (Glushkov’s automaton).**

The [Glushkov automaton](#def-b2-regular-languages-glushkov) of an expression with $m$ positions has $m + 1$ states, no [spontaneous transition](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-epsilon), and at most $m(m + 1)$ transitions, and it recognises $L(e)$.

**Proof.** The counts come from the definition. For the language, first show by structural induction that $L(e')$ is [local](#def-b2-regular-languages-local) with $P = \mathrm{First}$, $S = \mathrm{Last}$ and $F = \{ij : j \in \mathrm{Follow}(i)\}$, and that the sets computed by [Method 22.7](#met-b2-regular-languages-berry-sethi) are these. For a position, both are clear. For $f \mid g$, the positions of $f$ and $g$ are disjoint, no follow pair joins them, so a nonempty word passing the window test uses the positions of one side only and belongs to it. For $fg$, a word passing the test splits at the only pair $ij$ with $i$ in $f$ and $j$ in $g$, which the method added exactly for $i \in \mathrm{Last}(f)$, $j \in \mathrm{First}(g)$; the two parts pass the tests of $f$ and $g$, or one part is empty and its side nullable. For $f^*$, a word passing the test splits at the pairs $ij$ with $i \in \mathrm{Last}(f)$, $j \in \mathrm{First}(f)$ added by the star, into words of $L(f')$; and conversely every word of these languages passes the test. Finally, a run of the automaton on $w = a_1 \cdots a_k$ from 0 visits positions $j_1, \dots, j_k$ with $\ell(j_t) = a_t$, $j_1 \in \mathrm{First}$ and each $j_{t+1} \in
\mathrm{Follow}(j_t)$; it accepts when $j_k \in \mathrm{Last}$ (or $k = 0$ and $\mathrm{Null}$). So the automaton accepts $w$ exactly when $w$ is the image of a word of the [local language](#def-b2-regular-languages-local) $L(e')$, that is, $w \in L(e)$. ∎

Thompson’s automaton for $(a \mid b)^*abb$ has 20 states; Glushkov’s has 6:

```
$ rustc --edition 2021 -O -o thompson thompson.rs && ./thompson
expression          Thompson states  Glushkov states  agree up to length 7
(a|b)*abb                        20                6  true
a*b*c*                           16                4  true
(ab|b)*                          12                4  true
((a|b)(a|b))*                    16                5  true
a?b?c                            18                4  true
```

***Output 22.3.** Thompson’s construction, two states per node of the tree, against Glushkov’s $m + 1$, and the two automata compared on every word of length at most 7.*

The way back, from an automaton to an expression, labels transitions with expressions and removes the states one by one.

**Method 22.9 (State elimination).**

Given an automaton with states $1, \dots, n$, add a new start $S$ with $S \xrightarrow{\varepsilon}$ the old start and a new end $E$ with $q \xrightarrow{\varepsilon} E$ for every accepting $q$. Label each pair $(i, j)$ by an expression $r_{ij}$: the alternation of the letters from $i$ to $j$, or $\emptyset$. Then, for $k = 1, \dots, n$, remove state $k$: for every pair $(i, j)$ of remaining states, replace

$$
r_{ij} \quad\text{by}\quad r_{ij} \mid r_{ik}\, r_{kk}^*\, r_{kj}.
$$

At the end only $S$ and $E$ remain, and $r_{SE}$ denotes the language of the automaton.

![State elimination in three steps. Removing 0 reroutes S 0 1 into a*b (the loop a on 0 becomes a*) and 1 0 1 into aa*b, joined to the loop b.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-regular-languages/fig-612cfc1ac249.svg)

*State elimination in three steps. Removing 0 reroutes $S \to 0 \to 1$ into $a^*b$ (the loop $a$ on 0 becomes $a^*$) and $1 \to 0 \to 1$ into $aa^*b$, joined to the loop $b$.*

The loop in `dfa.rs`, the second library of the chapter, is the formula of the method; the smart constructors `cat`, `alt` and `star` of `regex.rs` drop the $\emptyset$ and $\varepsilon$ that would otherwise fill the result:

```rust
/// State elimination: edges labelled by expressions, a new start S and end E; remove
/// the states one by one, rerouting every path through the removed state.
pub fn eliminate(d: &Dfa) -> Re {
    let n = d.delta.len();
    let (s, e) = (n, n + 1);
    let mut r = vec![vec![Re::Empty; n + 2]; n + 2];
    for (q, row) in d.delta.iter().enumerate() {
        for (a, &t) in row.iter().enumerate() {
            r[q][t] = alt(r[q][t].clone(), Re::Char(d.alphabet[a]));
        }
        if d.accept[q] {
            r[q][e] = Re::Eps;
        }
    }
    r[s][0] = Re::Eps;
    for k in 0..n {
        let loop_k = star(r[k][k].clone());
        for i in k + 1..n + 2 {
            for j in k + 1..n + 2 {
                let through = cat(cat(r[i][k].clone(), loop_k.clone()), r[k][j].clone());
                r[i][j] = alt(r[i][j].clone(), through); // i -> k, loops on k, k -> j
            }
        }
    }
    r[s][e].clone()
}
```

***Listing 22.5.** State elimination on a complete DFA code/bachelor-2/22-regular-languages/listings/dfa.rs*

```
$ rustc --edition 2021 -O -o eliminate eliminate.rs && ./eliminate
expression: 0*|0*1(10*1)*10*|0*1(10*1)*0(1|0(10*1)*0)*0(10*1)*10*
matches exactly the multiples of 3 among 0 .. 4095: true
```

***Output 22.4.** The three-state automaton of the binary multiples of 3 ([Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata)), turned into an expression and checked.*

**Theorem 22.10 (Kleene’s theorem).**

A language is [regular](#def-b2-regular-languages-regular) if and only if it is [recognisable](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-recognisable) by a finite automaton.

**Proof.** If $L = L(e)$, the [Glushkov automaton](#def-b2-regular-languages-glushkov) recognises it ([Proposition 22.8](#prop-b2-regular-languages-glushkov)). Conversely, take an automaton and run [Method 22.9](#met-b2-regular-languages-elimination). By induction on $k$: after states $1, \dots, k$ are removed, $r_{ij}$ denotes the set of words that lead from $i$ to $j$ through intermediate states among $1, \dots, k$ only. True for $k = 0$, where there is no intermediate state. A path from $i$ to $j$ through $1, \dots, k$ either avoids $k$, and is counted by the old $r_{ij}$, or cuts at its visits to $k$ into a piece from $i$ to $k$, any number of loops from $k$ to $k$, and a piece from $k$ to $j$, each avoiding $k$ inside: that is $r_{ik} r_{kk}^* r_{kj}$. At the end, $r_{SE}$ denotes the words leading from $S$ to $E$, which are the accepted words. ∎

With [Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata), [regular languages](#def-b2-regular-languages-regular) are therefore closed under complement and intersection too, though expressions have no operator for either: the way goes through automata.

**History.**

Stephen Kleene introduced [regular expressions](#def-b2-regular-languages-regex) and proved the theorem in his paper of 1956 on nerve nets and finite automata. Victor Glushkov’s position automaton appeared in his 1961 survey of the theory of automata. Ken Thompson published his construction in 1968, in a short paper on searching text for a [regular expression](#def-b2-regular-languages-regex), where the NFA is simulated on all its states at once. Gérard Berry and Ravi Sethi showed in 1986 how to compute the positions’ sets on the expression directly, as in [Method 22.7](#met-b2-regular-languages-berry-sethi).

## 22.3 The minimal automaton

Many automata recognise the same language. What a DFA must remember after reading $u$ is what the rest of the word needs to know.

**Definition 22.11 (Residual, Myhill–Nerode equivalence).**

The *residual* (or left quotient) of a language $L$ by a word $u$ is $u^{-1}L = \{v :
uv \in L\}$. Two words are *equivalent for $L$*, $u \sim_L v$, if $u^{-1}L =
v^{-1}L$: no continuation $x$ tells them apart, $ux \in L \iff vx \in L$.

For $L = (ab \mid b)^*$: $\varepsilon^{-1}L = L$, $a^{-1}L = bL$, $(aa)^{-1}L = \emptyset$, and $b^{-1}L = (ab)^{-1}L =
L$. Every word has one of these three [residuals](#def-b2-regular-languages-residual).

**Theorem 22.12 (Myhill–Nerode).**

A language $L$ is [recognisable](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-recognisable) if and only if it has finitely many [residuals](#def-b2-regular-languages-residual). Every complete DFA for $L$ has at least as many [accessible states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-trim) as $L$ has [residuals](#def-b2-regular-languages-residual), and the *[residual](#def-b2-regular-languages-residual) automaton* reaches the bound: its states are the [residuals](#def-b2-regular-languages-residual), its start is $L$, its transitions are $R \xrightarrow{a} a^{-1}R$, and its [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) are the [residuals](#def-b2-regular-languages-residual) that contain $\varepsilon$.

**Proof.** Let $A$ be a complete DFA for $L$ and $L_q$ the language it accepts from state $q$. Then $u^{-1}L = L_{\delta^*(q_0,
u)}$: $uv$ is accepted exactly when $v$ leads $\delta^*(q_0, u)$ to an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) ([Proposition 21.5](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#prop-b2-finite-automata-extended)). So each [residual](#def-b2-regular-languages-residual) is $L_q$ for some accessible $q$, and there are at most as many [residuals](#def-b2-regular-languages-residual) as [accessible states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-trim). Conversely, suppose there are finitely many [residuals](#def-b2-regular-languages-residual). Since $a^{-1}(u^{-1}L) =
(ua)^{-1}L$, the transitions of the [residual](#def-b2-regular-languages-residual) automaton lead from a [residual](#def-b2-regular-languages-residual) to a [residual](#def-b2-regular-languages-residual), and by induction on $|w|$ its run on $w$ from $L$ ends in $w^{-1}L$. It accepts $w$ when $\varepsilon \in w^{-1}L$, that is, when $w \in L$. ∎

**Definition 22.13 (Minimal automaton).**

A complete DFA for $L$ is *minimal* if no complete DFA for $L$ has fewer states. By the theorem, the [residual](#def-b2-regular-languages-residual) automaton is minimal; it is called *the* minimal automaton of $L$.

**Corollary 22.14 (Uniqueness).**

Every [minimal](#def-b2-regular-languages-minimal) complete DFA for $L$ equals the [residual](#def-b2-regular-languages-residual) automaton up to the names of its states.

**Proof.** In a [minimal](#def-b2-regular-languages-minimal) DFA $A$ every state is accessible, or removing it would leave a smaller complete DFA. The map $q \mapsto
L_q$ sends each state to a [residual](#def-b2-regular-languages-residual), reaches them all, and so is a bijection, since both sets have the same size. It respects the start ($L_{q_0} = L$), the [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) ($q \in F$ iff $\varepsilon \in L_q$) and the transitions ($L_{\delta(q, a)} = a^{-1}L_q$). ∎

Two states $p$ and $q$ of a DFA can be merged when $L_p = L_q$. Moore’s method finds these pairs by looking further and further ahead.

**Method 22.15 (Moore’s minimisation).**

Start from an accessible complete DFA with $n$ states. Round 0 splits the states into two classes, accepting or not. Round $k + 1$ puts $p$ and $q$ in the same class when they were in the same class at round $k$ and, for every letter $a$, so were $\delta(p, a)$ and $\delta(q, a)$. Stop at the first round that splits no class. Merging each final class into one state gives the [minimal automaton](#def-b2-regular-languages-minimal).

**Correctness.** By induction on $k$, $p$ and $q$ share a class at round $k$ exactly when no word of length at most $k$ is accepted from one and not from the other. A round that splits nothing gives the same partition at every later round, since a round depends only on the previous one; so the final classes are those of $L_p = L_q$. Merging them gives a well defined DFA, since equivalent states have equivalent successors, with one state per [residual](#def-b2-regular-languages-residual) of $L$: the [minimal automaton](#def-b2-regular-languages-minimal). Each round but the last adds a class, and there are at most $n$, so there are at most $n$ rounds, each in time proportional to $n|\Sigma|$. ∎

```rust
/// Moore: start from {accepting, other}; split classes by the classes of the successors
/// until nothing splits. Returns the class of each state after each round.
pub fn moore(d: &Dfa) -> Vec<Vec<usize>> {
    let renumber = |keys: Vec<Vec<usize>>| {
        let mut seen = HashMap::new();
        keys.into_iter().map(|k| {
            let n = seen.len();
            *seen.entry(k).or_insert(n) // a new key gets the next number
        }).collect()
    };
    let first = d.accept.iter().map(|&a| vec![a as usize]).collect();
    let mut rounds: Vec<Vec<usize>> = vec![renumber(first)];
    loop {
        let class = rounds.last().unwrap();
        let keys = (0..d.delta.len())
            .map(|q| {
                let succ = d.delta[q].iter().map(|&r| class[r]);
                std::iter::once(class[q]).chain(succ).collect() // own class, then successors'
            })
            .collect();
        let next: Vec<usize> = renumber(keys);
        let count = |c: &Vec<usize>| c.iter().max().map_or(0, |m| m + 1);
        if count(&next) == count(class) {
            return rounds; // stable: the classes are those of the minimal automaton
        }
        rounds.push(next);
    }
}
```

***Listing 22.6.** Moore’s rounds: a state’s new class is named by its old class and its successors’ classes code/bachelor-2/22-regular-languages/listings/dfa.rs*

The determinised [Glushkov automaton](#def-b2-regular-languages-glushkov) of “starts with $a$, or starts and ends with $b$” has 7 states; two rounds leave 4 classes:

```
$ rustc --edition 2021 -O -o minimise minimise.rs && ./minimise
state  on a  on b  accepting
    0     1     2  false
    1     3     4  true
    2     5     6  true
    3     3     4  true
    4     3     4  true
    5     5     6  false
    6     5     6  true
round 0: classes [0, 1, 1, 1, 1, 0, 1]
round 1: classes [0, 1, 2, 1, 1, 3, 2]
minimal automaton: 4 states, from 7
```

***Output 22.5.** The DFA of $a(a \mid b)^* \mid b(a \mid b)^*b
\mid b$, Moore’s classes round by round, and the result.*

![The minimal automaton: each state is a class of . In \2, 6\ the last letter read is a b after a first b; in \5\ it is an a.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-regular-languages/fig-e9cab57aa320.svg)

*The [minimal automaton](#def-b2-regular-languages-minimal): each state is a class of [Output 22.5](#out-b2-regular-languages-minimise). In $\{2, 6\}$ the last letter read is a $b$ after a first $b$; in $\{5\}$ it is an $a$.*

Moore’s method can need $n$ rounds, on an automaton shaped as a chain, and then costs time proportional to $n^2|\Sigma|$. John Hopcroft’s algorithm reaches $n |\Sigma| \log n$: it keeps a list of *splitters*, a class and a letter, splits every class by “enters the splitter on that letter or not”, and when a class splits in two puts only the smaller half on the list. A state then joins a splitter at most $\log_2 n$ times, since each time its class at least halves ([Exercise 22.11](#exo-b2-regular-languages-11)).

## 22.4 The limits of regular languages

A finite automaton has a finite memory. A language that needs to count without bound is not [regular](#def-b2-regular-languages-regular).

**Theorem 22.16 (Pumping lemma).**

If $L$ is recognised by a DFA with $p$ states, every word $w \in L$ with $|w| \ge p$ can be written $w = xyz$ with $|xy| \le p$ and $y \ne \varepsilon$, so that $xy^kz \in L$ for every $k \ge 0$.

**Proof.** The run on the first $p$ letters of $w$ visits $p + 1$ states, so one state $q$ appears twice, after reading $x$ and after reading $xy$, with $|xy| \le p$ and $y$ nonempty. Reading $y$ leads $q$ back to $q$, so it can be read any number of times, zero included, and the run on $xy^kz$ ends where the run on $w$ ends, in an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa). ∎

**Proposition 22.17 (Three languages that are not regular).**

The languages $\{a^n b^n : n \ge 0\}$, the balanced bracket words over $\{(, )\}$, and the palindromes over $\{a, b\}$ are not [regular](#def-b2-regular-languages-regular).

**Proof.** For $\{a^nb^n\}$, by the pumping lemma: if a DFA with $p$ states recognised it, $w = a^pb^p$ would split with $y =
a^j$, $j \ge 1$, since $|xy| \le p$; but $xy^2z = a^{p+j}b^p$ is not in the language. Also by [Theorem 22.12](#thm-b2-regular-languages-myhill-nerode): for $i \ne j$, $b^i$ is in the [residual](#def-b2-regular-languages-residual) by $a^i$ and not in the [residual](#def-b2-regular-languages-residual) by $a^j$, so the [residuals](#def-b2-regular-languages-residual) are infinitely many. Balanced brackets: their intersection with the [regular language](#def-b2-regular-languages-regular) $(^*\,)^*$ is $\{(^n )^n\}$, which is $\{a^nb^n\}$ with other letters; if they were [regular](#def-b2-regular-languages-regular), so would be the intersection. Palindromes: for $i \ne j$, $ba^i$ is in the [residual](#def-b2-regular-languages-residual) by $a^ib$ and not in the [residual](#def-b2-regular-languages-residual) by $a^jb$. ∎

The pumping lemma gives only a necessary condition: some languages that are not [regular](#def-b2-regular-languages-regular) can be pumped. The [residuals](#def-b2-regular-languages-residual) give the exact answer, and with them a proof is a matter of finding infinitely many words that pairwise differ in what must follow. A back-reference that repeats a group asks for the language $\{ww\}$, which has infinitely many [residuals](#def-b2-regular-languages-residual) (by $a^ib$, as for palindromes); this is why pattern engines with back-references cannot be finite automata. Balanced brackets and arithmetic expressions need the grammars of [Chapter 23](https://one-course.com/books/computer-science/4/en/chapter/23-context-free-grammars-and-pushdown-automata#ch-b2-context-free-languages).

**History.**

The equivalence and the theorem carry the names of John Myhill and Anil Nerode; Nerode’s paper appeared in 1958. The pumping lemma for [regular languages](#def-b2-regular-languages-regular) is a direct form of the pigeonhole argument used in its proof.

## 22.5 Deciding questions about automata

Because an automaton is a finite object, many questions about the infinite language it recognises can be answered by a program that always stops.

**Proposition 22.18 (Questions and their costs).**

For complete DFAs $A$ and $B$ with $n_A$ and $n_B$ states over $\Sigma$:

- *membership* of a word $w$ : time proportional to $|w|$ ;
- *emptiness* , $L(A) = \emptyset$ : no [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) is accessible, a graph search in time proportional to $n_A|\Sigma|$ ;
- *finiteness* : $L(A)$ is infinite exactly when the [trim automaton](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-trim) has a cycle, also a graph search;
- *inclusion* , $L(A) \subseteq L(B)$ : $L(A) \cap (\Sigma^* \setminus L(B))$ is empty, a search of the product in time proportional to $n_A n_B |\Sigma|$ ;
- *equivalence* : no accessible pair $(p, q)$ of the product has $p$ accepting and $q$ not, or the reverse; a breadth-first search finds a shortest word on which they differ, if there is one.

**Proof.** Membership is the run. Emptiness: a word is accepted exactly when its run reaches an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa), so $L(A)$ is nonempty exactly when an [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) is accessible. Finiteness: in the [trim automaton](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-trim) every path extends into an accepted word; a cycle gives infinitely many paths, and without a cycle every path has fewer than $n_A$ transitions, so the accepted words are shorter than $n_A$ and finitely many. Inclusion is emptiness of the product for intersection with the complement ([Proposition 21.17](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#prop-b2-finite-automata-closure)), and equivalence is two inclusions, read on the same product: the pair after $w$ is $(\delta_A^*(q_A, w), \delta_B^*(q_B, w))$, and $w$ separates the languages exactly when one of the two states accepts and the other does not. ∎

From expressions, these questions go through automata. The [Glushkov automaton](#def-b2-regular-languages-glushkov) is built in time proportional to $m^2$ and decides membership by simulation in at most $(m + 1)|w|$ steps; but inclusion and equivalence need complete DFAs, and determinisation may cost exponentially many states ([Theorem 21.15](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#thm-b2-finite-automata-blowup)). For short patterns it is fast:

```
$ rustc --edition 2021 -O -o equivalent equivalent.rs && ./equivalent
(a|b)*     = (a*b*)*
(ab)*a     = a(ba)*
a*b*       differs from (a|b)*: on "ba"
(a|b)*abb  differs from (a|b)*bb: on "bb"
(aa|a)*    = a*
```

***Output 22.6.** Five pairs of expressions, compared through their determinised Glushkov automata, with a shortest witness when they differ.*

The witness `"bb"` is in the language of $(a \mid b)^*bb$ but does not end with $abb$. The checker itself is [Exercise 22.9](#exo-b2-regular-languages-9). By [Corollary 22.14](#cor-b2-regular-languages-unique-minimal), a second way to compare is to minimise both automata and compare them state by state.

## 22.6 A pattern engine that cannot freeze

The engine of `regex.rs` parses the pattern into a tree, computes Glushkov’s sets, and simulates the automaton on sets of states, as [Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata) simulated NFAs. With at most 127 positions, a set of states is the bits of one 128-bit integer; for each letter, the next set is the union of the successors of the current states, kept only at positions holding that letter:

```rust
impl Matcher {
    pub fn new(g: &Glushkov) -> Matcher {
        assert!(g.letters.len() < 128, "at most 127 positions");
        let bits = |s: &BTreeSet<usize>| s.iter().fold(0u128, |m, &j| m | 1 << j);
        let mut succ = vec![bits(&g.first)];
        succ.extend(g.follow[1..].iter().map(bits));
        let mut with = std::collections::HashMap::new();
        for (j, &c) in g.letters.iter().enumerate() {
            *with.entry(c).or_insert(0) |= 1u128 << (j + 1);
        }
        Matcher { succ, with, accept: bits(&g.last) | g.nullable as u128 }
    }

    /// Accept or not, and the number of steps: at most m + 1 ORs per letter.
    pub fn run(&self, word: &str) -> (bool, usize) {
        let (mut set, mut steps) = (1u128, 0); // {0}
        for c in word.chars() {
            let mut next = 0;
            let mut rest = set;
            while rest != 0 {
                next |= self.succ[rest.trailing_zeros() as usize];
                rest &= rest - 1;
                steps += 1;
            }
            set = next & self.with.get(&c).copied().unwrap_or(0);
        }
        (set & self.accept != 0, steps)
    }
```

***Listing 22.7.** The matcher: one OR per current state, then a mask for the letter code/bachelor-2/22-regular-languages/listings/regex.rs*

**Proposition 22.19 (Linear matching).**

On an expression with $m$ positions and a text of $n$ letters, the matcher performs at most $(m + 1)n$ unions, whatever the expression and the text.

**Proof.** Each letter costs one union per state of the current set, and the set holds at most the $m + 1$ states. The set after $k$ letters is the set of states the [Glushkov automaton](#def-b2-regular-languages-glushkov) can reach on the first $k$ letters, by induction on $k$, so the answer is that of the automaton, which is correct by [Proposition 22.8](#prop-b2-regular-languages-glushkov). ∎

On $(a \mid a)^*b$, with positions $a_1$, $a_2$, $b_3$, the set after each $a$ is $\{1, 2\}$, and every letter costs two unions:

```
$ rustc --edition 2021 -O -o engine_compare engine_compare.rs && ./engine_compare
        n   matched      steps   steps/letter   time (ms)
       20 false             39           1.95       0.000
       24 false             47           1.96       0.000
     1000 false           1999           2.00       0.007
  1000000 false        1999999           2.00       7.255
 10000000 false       19999999           2.00      73.370
```

***Output 22.7.** The matcher on $(a \mid a)^*b$ and $a^n$, on the laptop.*

![Time to answer “no match” for (a a)*b on an, on a logarithmic scale: the backtracking engine’s points () climb on a straight line, doubling with each a; the matcher’s line is its measured cost per letter on ten million letters (), times n.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-regular-languages/fig-80e14da36d7a.svg)

*Time to answer “no match” for $(a \mid a)^*b$ on $a^n$, on a logarithmic scale: the backtracking engine’s points ([Output 22.1](#out-b2-regular-languages-hook)) climb on a straight line, doubling with each $a$; the matcher’s line is its measured cost per letter on ten million letters ([Output 22.7](#out-b2-regular-languages-engine)), times $n$.*

A backtracking engine tries one way to match at a time: on $a^n$, each $a$ can be matched by the left or the right branch of $(a \mid a)$, and when the missing $b$ makes a choice fail, the engine goes back to the last choice and tries the other. The $2^n$ ways to read $a^n$ all fail, and it tries them all. The automaton keeps every way at once, in a set that never holds more than $m + 1$ states. Backtracking has reasons: it reports which part of the text each group matched, in the order a programmer expects, and it supports back-references, which no automaton can. Engines built on automata, in the line of Thompson’s, give up back-references and in exchange answer in linear time.

**Facts as of 2026.**

Python’s `re` module is a backtracking engine. Since version 3.11 it offers possessive quantifiers such as `a*+` and atomic groups, which throw away the backtracking points inside them and can stop a blow-up like the hook’s when the pattern’s author sees it coming. The POSIX standard defines basic and [extended regular expressions](#def-b2-regular-languages-extended) for tools such as `grep`, and asks, when several matches start at the same point, for the longest.

On the town’s 24 street names, the engine answers patterns that expand to a hundred positions, since a range such as `[A-Z]` is an alternation of 26 letters:

```rust
// streets.rs: patterns over the town's street names.
#[allow(dead_code)]
mod regex;

fn main() {
    let table = std::fs::read_to_string("../../../../data/town/streets.csv").unwrap();
    let names: Vec<&str> = table.lines().skip(1)
        .map(|line| line.split(',').nth(1).unwrap()).collect();
    let patterns = ["[A-Z][a-z]* Road", "[A-Z][a-z]* (Road|Row|Way)",
                    "(Mill|River) [A-Za-z]*", "[A-Z][a-z]*(e|n) [A-Z][a-z]*",
                    "[A-Z][a-z]* [A-Z][a-z]*"];
    for pattern in patterns {
        let re = regex::parse(pattern).unwrap();
        let g = regex::glushkov(&re);
        let m = regex::Matcher::new(&g);
        let hits: Vec<&str> = names.iter().copied().filter(|n| m.matches(n)).collect();
        let some = hits.iter().take(2).copied().collect::<Vec<_>>().join(", ");
        let (m, k) = (g.letters.len(), hits.len());
        println!("{pattern:31} {m:3} positions {k:3} of {}: {some}", names.len());
    }
}
```

***Listing 22.8.** Five patterns over the street names code/bachelor-2/22-regular-languages/listings/streets.rs*

```
$ rustc --edition 2021 -O -o streets streets.rs && ./streets
[A-Z][a-z]* Road                 57 positions   4 of 24: Bridge Road, Castle Road
[A-Z][a-z]* (Road|Row|Way)       63 positions  14 of 24: Bridge Road, Bridge Way
(Mill|River) [A-Za-z]*           62 positions   5 of 24: Mill Avenue, Mill Row
[A-Z][a-z]*(e|n) [A-Z][a-z]*    107 positions   8 of 24: Bridge Road, Bridge Way
[A-Z][a-z]* [A-Z][a-z]*         105 positions  24 of 24: Bridge Road, Bridge Way
```

***Output 22.8.** The number of positions of each pattern, the number of names it matches, and the first two.*

## 22.7 Exercises

**Exercise 22.1 ★.**

Which of the words $\varepsilon$, $a$, $aa$, $bab$, $abba$, $babab$, $aab$ are in $L((ab \mid b)^*a?)$? Describe the language in words, then check with the engine.

**Solution of Exercise 22.1.**

```
$ rustc --edition 2021 -O -o exo_match exo_match.rs && ./exo_match
""       true
"a"      true
"aa"     false
"bab"    true
"abba"   true
"babab"  true
"aab"    false
```

***Output 22.9.** The seven words.*

$(ab \mid b)^*$ is the words in which every $a$ is immediately followed by a $b$, and the final $a?$ allows one more $a$ at the end. So $\varepsilon$, $a$, $bab$, $abba$ and $babab$ match; $aa$ and $aab$ do not, since their first $a$ is followed by an $a$.

**Exercise 22.2 ★.**

A tool checks variable names with the pattern `[a-z0-9_]+`. Find the names it wrongly accepts, and write a pattern that requires a first character that is not a digit.

**Solution of Exercise 22.2.**

```
$ rustc --edition 2021 -O -o exo_ident exo_ident.rs && ./exo_ident
"x"       [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"x9"      [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"9lives"  [a-z0-9_]+ true    [a-z_][a-z0-9_]* false
"_tmp"    [a-z0-9_]+ true    [a-z_][a-z0-9_]* true
"2"       [a-z0-9_]+ true    [a-z_][a-z0-9_]* false
""        [a-z0-9_]+ false   [a-z_][a-z0-9_]* false
```

***Output 22.10.** The two patterns on six names.*

`[a-z0-9_]+` accepts `9lives` and `2`, which start with a digit. The pattern `[a-z_][a-z0-9_]*` asks for one letter or underscore, then any number of letters, digits or underscores: it rejects them, and still rejects the empty name.

**Exercise 22.3 ★.**

Write an extended expression for the decimal numbers of [Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata)’s hook (an optional sign, digits, an optional point followed by digits, an optional exponent). Check it against the hook’s automaton on every string of length at most 6 over the characters `0 1 + - . e E`; in this chapter’s syntax, `.` is a plain letter.

**Solution of Exercise 22.3.**

```
$ rustc --edition 2021 -O -o exo_decimal exo_decimal.rs && ./exo_decimal
137257 strings, 1854 numbers, 0 disagreements
```

***Output 22.11.** The expression against the hook’s automaton.*

The expression is `[+-]?[0-9]+(.[0-9]+)?([eE][+-]?[0-9]+)?`: an optional sign, at least one digit, an optional group of a point and at least one digit, and an optional exponent with its own optional sign. It agrees with the automaton on all 137 257 strings of length at most 6 over the seven characters, 1 854 of which are numbers. A check on a finite set is not a proof; the proof is [Exercise 22.9](#exo-b2-regular-languages-9)’s checker, run on the two automata.

**Exercise 22.4 ★.**

Let $c_n$ be the number of words of length $n$ in $L((ab \mid b)^*)$. Find a recurrence for $c_n$, and check it on $c_0, \dots, c_{12}$.

**Solution of Exercise 22.4.**

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

***Output 22.12.** $c_0$ to $c_{12}$, from the denotation.*

A nonempty word of the language starts either with $b$, followed by any word of the language of length $n - 1$, or with $ab$, followed by one of length $n - 2$; the two cases do not overlap, since the first letter tells them apart. So $c_n = c_{n-1} + c_{n-2}$ with $c_0 = c_1 = 1$: the Fibonacci numbers.

**Exercise 22.5 ★★.**

Number the positions of $a(ba \mid b)^*a$ and compute $\mathrm{Null}$, $\mathrm{First}$, $\mathrm{Last}$ and every $\mathrm{Follow}$ set by [Method 22.7](#met-b2-regular-languages-berry-sethi). Draw the [Glushkov automaton](#def-b2-regular-languages-glushkov).

**Solution of Exercise 22.5.**

```
$ rustc --edition 2021 -O -o exo_follow exo_follow.rs && ./exo_follow
a1 b2 a3 b4 a5; nullable false; first {1}; last {5}
follow(1) = {2, 4, 5}
follow(2) = {3}
follow(3) = {2, 4, 5}
follow(4) = {2, 4, 5}
follow(5) = {}
```

***Output 22.13.** The sets of $a_1(b_2a_3 \mid b_4)^*a_5$.*

The star’s body has $\mathrm{First} = \{2, 4\}$ and $\mathrm{Last} = \{3, 4\}$; the star adds $\{2, 4\}$ to the follow sets of 3 and 4. The concatenation of $a_1$ with the star (nullable) gives $\mathrm{Follow}(1) = \{2, 4\}$, and the concatenation with $a_5$ adds 5 to the follow sets of 1, 3 and 4. Inside $b_2a_3$, $\mathrm{Follow}(2) = \{3\}$. The automaton has states 0 to 5: $0 \xrightarrow{a} 1$; from 1, 3 and 4: $b$ to 2, $b$ to 4 and $a$ to 5; $2
\xrightarrow{a} 3$; state 5 accepts.

**Exercise 22.6 ★★.**

A program minimises the incomplete DFA of $\{ab, ba\}$ (states 0, 1 after $a$, 2 after $b$, 3 accepting) by refining classes on the classes of the successors that exist, without completing it first. Which states does it merge, and which words does the merged automaton wrongly accept? How must the program be fixed?

**Solution of Exercise 22.6.**

```
$ rustc --edition 2021 -O -o exo_min_bug exo_min_bug.rs && ./exo_min_bug
classes: [0, 1, 1, 2]
ab: true
ba: true
aa: true
bb: true
```

***Output 22.14.** The classes found, and four words on the merged automaton.*

States 1 and 2 both have one successor, in the accepting class, so the program merges them; it forgot that state 1 moves on $b$ and state 2 on $a$. The merged automaton accepts $aa$ and $bb$ as well as $ab$ and $ba$. The fix is to complete the automaton first, with a sink, and to compare the successors letter by letter, as in [Listing 22.6](#lst-b2-regular-languages-moore): then 1 goes to the sink on $a$ and 2 goes to 3, and round 1 separates them.

**Exercise 22.7 ★★.**

Apply [Method 22.9](#met-b2-regular-languages-elimination) by hand to the two-state DFA of “an even number of $a$” over $\{a, b\}$, removing the start state first. Check the expression on every word of length at most 10.

**Solution of Exercise 22.7.**

```
$ rustc --edition 2021 -O -o exo_eliminate exo_eliminate.rs && ./exo_eliminate
b*|b*a(b|ab*a)*ab*
right on all 2047 words up to length 10: true
```

***Output 22.15.** The expression found by `eliminate`, and its check.*

State 0 (even) is the start and accepts; $r_{00} = b$, $r_{01} = a$, $r_{10} = a$, $r_{11} = b$, with $S
\xrightarrow{\varepsilon} 0$ and $0 \xrightarrow{\varepsilon} E$. Removing 0 gives $r_{SE} = b^*$, $r_{S1} = b^*a$, $r_{11} = b \mid ab^*a$ and $r_{1E} = ab^*$. Removing 1 gives $r_{SE} = b^* \mid b^*a(b \mid ab^*a)^*ab^*$: no $a$, or a first $a$, blocks with an even number of $a$, and a last $a$.

**Exercise 22.8 ★★.**

Prove that $\{a^n b^m : n \le m\}$ is not [regular](#def-b2-regular-languages-regular), once with the pumping lemma and once with [residuals](#def-b2-regular-languages-residual).

**Solution of Exercise 22.8.**

Let $L = \{a^nb^m : n \le m\}$. Pumping: if a DFA with $p$ states recognised $L$, then $w = a^pb^p \in L$ would split as $xyz$ with $|xy| \le p$, so $y = a^j$ with $j \ge 1$, and $xy^2z = a^{p+j}b^p$ would be in $L$; it is not, since $p + j > p$. [Residuals](#def-b2-regular-languages-residual): for $i < j$, $b^i$ is in $(a^i)^{-1}L$ but not in $(a^j)^{-1}L$, so the words $a^0, a^1,
a^2, \dots$ have pairwise different [residuals](#def-b2-regular-languages-residual), infinitely many, and [Theorem 22.12](#thm-b2-regular-languages-myhill-nerode) concludes.

**Exercise 22.9 ★★.**

Write a function that takes two complete DFAs over the same [alphabet](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) and returns either “equivalent” or a shortest word on which they differ. Use it to compare expressions through their Glushkov automata.

**Solution of Exercise 22.9.**

```rust
/// None if the two automata recognise the same language, else a shortest word on which
/// they differ: a breadth-first search over the pairs of states.
pub fn difference(x: &Dfa, y: &Dfa) -> Option<String> {
    let mut seen = HashMap::from([((0, 0), String::new())]);
    let mut todo = VecDeque::from([(0, 0)]);
    while let Some((p, q)) = todo.pop_front() {
        let w = seen[&(p, q)].clone();
        if x.accept[p] != y.accept[q] {
            return Some(w);
        }
        for (a, &c) in x.alphabet.iter().enumerate() {
            let next = (x.delta[p][a], y.delta[q][a]);
            if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(next) {
                e.insert(format!("{w}{c}")); // a shortest word reaching this pair
                todo.push_back(next);
            }
        }
    }
    None
}
```

*A breadth-first search over pairs of states code/bachelor-2/22-regular-languages/listings/dfa.rs*

The search starts from the pair of start states and follows each letter in both automata at once: this is the [product automaton](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-product), built only as far as it is reached. Each pair is entered once, with the word that first reached it; since a breadth-first search reaches pairs in order of the length of that word, the first pair with different acceptance gives a shortest word on which the languages differ. If no such pair is reached, the languages are equal ([Proposition 22.18](#prop-b2-regular-languages-decisions)). The cost is at most $n_A n_B |\Sigma|$ steps. [Output 22.6](#out-b2-regular-languages-equivalent) shows it on five pairs of expressions.

**Exercise 22.10 ★★★.**

Show that $\sim_L$ is a *right congruence*: $u \sim_L v$ implies $ua \sim_L va$ for every letter $a$. Deduce that if $L$ is [regular](#def-b2-regular-languages-regular), the classes of $\sim_L$ are in bijection with the states of the [minimal automaton](#def-b2-regular-languages-minimal), $u \sim_L v$ holding exactly when $u$ and $v$ lead it to the same state.

**Solution of Exercise 22.10.**

If $u^{-1}L = v^{-1}L$, then $(ua)^{-1}L = a^{-1}(u^{-1}L) = a^{-1}(v^{-1}L) = (va)^{-1}L$, since $x \in (ua)^{-1}L$ iff $uax \in L$ iff $ax \in u^{-1}L$. So $\sim_L$ is a right congruence. By definition, the classes of $\sim_L$ are in bijection with the [residuals](#def-b2-regular-languages-residual), by $[u] \mapsto u^{-1}L$. By [Corollary 22.14](#cor-b2-regular-languages-unique-minimal), the [minimal automaton](#def-b2-regular-languages-minimal) is the [residual](#def-b2-regular-languages-residual) automaton, whose run on $u$ ends in $u^{-1}L$ ([Theorem 22.12](#thm-b2-regular-languages-myhill-nerode)). So $u$ and $v$ lead it to the same state exactly when $u^{-1}L =
v^{-1}L$, that is, when $u \sim_L v$, and the number of classes, the *index* of $\sim_L$, is the number of states of the [minimal automaton](#def-b2-regular-languages-minimal).

**Exercise 22.11 ★★★.**

Implement Hopcroft’s algorithm: keep a list of splitters (a class and a letter); for a splitter $(B, a)$, split each class into the states that enter $B$ on $a$ and the others; when a class splits, put both halves on the list if it was there, and otherwise only the smaller half. Check that it finds Moore’s classes, and compare the two on large automata. Why is the gain so small here?

**Solution of Exercise 22.11.**

```rust
    let smaller = (0..blocks.len()).min_by_key(|&i| blocks[i].len()).unwrap();
    let mut work: HashSet<(usize, usize)> = (0..k).map(|a| (smaller, a)).collect();
    let mut hit = vec![false; n]; // marks, cleared after each splitter
    while let Some(&(b, a)) = work.iter().next() {
        work.remove(&(b, a));
        let mut entering: Vec<usize> = blocks[b].iter() // the states entering b on a
            .flat_map(|&q| inv[a][q].iter().copied()).collect();
        entering.iter().for_each(|&p| hit[p] = true);
        entering.sort_by_key(|&p| block_of[p]);
        let mut touched: Vec<usize> = entering.iter().map(|&p| block_of[p]).collect();
        touched.dedup();
        for y in touched {
            let (inside, outside): (Vec<usize>, Vec<usize>) =
                blocks[y].iter().partition(|&&q| hit[q]);
            if outside.is_empty() {
                continue; // y lies entirely in the preimage: no split
            }
            let z = blocks.len(); // y keeps `inside`, the new block z gets `outside`
            outside.iter().for_each(|&q| block_of[q] = z);
            let small = if inside.len() <= outside.len() { y } else { z };
            blocks[y] = inside;
            blocks.push(outside);
            for c in 0..k {
                if work.contains(&(y, c)) {
                    work.insert((z, c)); // both halves still to be used
                } else {
                    work.insert((small, c)); // the smaller half is enough
                }
            }
        }
        entering.iter().for_each(|&p| hit[p] = false);
    }
```

*Hopcroft’s loop: splitters, the states entering them, and the smaller half code/bachelor-2/22-regular-languages/exercises/hopcroft.rs*

```
$ rustc --edition 2021 -O -o minimise_bench minimise_bench.rs && ./minimise_bench
 k   DFA states  minimal  Moore rounds  Moore (ms)  Hopcroft (ms)
 8          769      511             9         0.5            0.4
10         3073     2047            11         2.3            1.8
12        12289     8191            13        13.2            8.4
14        49153    32767            15        74.2           52.2
```

***Output 22.16.** Moore and Hopcroft on automata of up to 49 153 states, on the laptop.*

The predecessor lists `inv` let a splitter $(B, a)$ cost the number of transitions entering $B$ on $a$. A state $q$ lies in a splitter on the list once per time its class is put there, and after its first time it is put there only as the smaller half, at most half of the previous class: at most $1 + \log_2 n$ times per letter. Summed over the states, the work is proportional to $n|\Sigma| \log n$. The tests check that the classes are Moore’s on every sample. Here Hopcroft’s algorithm gains less than a factor of 2 (between 1.25 and 1.6 in the run printed): Moore’s method needs only $k + 1$ rounds on these automata, about $\log_2 n$, so both do about $n \log
n$ work, and Hopcroft’s bookkeeping (a set of splitters, predecessor lists, sorting) costs more per step. On an automaton that is a chain of $n$ states, Moore needs about $n$ rounds and the difference becomes large.

**Exercise 22.12 ★★★.**

Prove that $\{w \in \{a, b\}^* : w \text{ has as many } a \text{ as } b\}$ is not [regular](#def-b2-regular-languages-regular), once with [residuals](#def-b2-regular-languages-residual) and once by intersecting it with $a^*b^*$.

**Solution of Exercise 22.12.**

Let $L$ be the words with as many $a$ as $b$. [Residuals](#def-b2-regular-languages-residual): for $i \ne j$, $b^i \in (a^i)^{-1}L$ and $b^i \notin
(a^j)^{-1}L$, so $L$ has infinitely many [residuals](#def-b2-regular-languages-residual). Intersection: $L \cap a^*b^* = \{a^nb^n\}$, which is not [regular](#def-b2-regular-languages-regular) ([Proposition 22.17](#prop-b2-regular-languages-nonregular)); since $a^*b^*$ is [regular](#def-b2-regular-languages-regular) and [regular languages](#def-b2-regular-languages-regular) are closed under intersection, $L$ cannot be [regular](#def-b2-regular-languages-regular).

## 22.8 Problem: A search box that never freezes

**Problem 22.1.**

Weekend problem — A search box that never freezes

The town’s website lets visitors search the street names with patterns. The first version used a backtracking engine, and a visitor froze it. This problem builds the replacement. The 24 names are Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Church Lane, Church Way, Garden Lane, Garden Road, Market Road, Market Row, Mill Avenue, Mill Row, Mill Street, Orchard Lane, Orchard Row, Orchard Way, River Avenue, River Lane, School Avenue, School Lane, School Way, Station Row and Willow Lane.

**Part I — Patterns over the street names.**

1. How many names end in Road, in Row and in Way? Compare with [Output 22.8](#out-b2-regular-languages-streets) .
2. Why does `[A-Z][a-z]* Road` have 57 positions?
3. Write a pattern for the names whose second word is Lane or Avenue. How many names does it match?
4. List the 8 names matched by `[A-Z][a-z]*(e|n) [A-Z][a-z]*` .
5. Show that any finite set of names is a [regular language](#def-b2-regular-languages-regular) .
6. A search box looks for the pattern anywhere in a name. Which expression, built from $e$ , denotes the names that contain a match of $e$ ?

**Part II — The Glushkov engine.**

Let $e = (ab \mid b)^*c$ over $\{a, b, c\}$.

7. Number the positions of $e$ and give $\mathrm{Null}$ , $\mathrm{First}$ , $\mathrm{Last}$ and the follow sets.
8. How many states and transitions does its [Glushkov automaton](#def-b2-regular-languages-glushkov) have?
9. Give the matcher’s set of states after each letter of $babbc$ . Is the word accepted, and how many unions were made?
10. Show that after reading a letter, every state in the set is a position holding that letter.
11. At most how many unions does the matcher make on a name of 12 letters with the pattern `[A-Z][a-z]* Road` ?
12. Why does the matcher refuse patterns with more than 127 positions, and how would you lift the limit?

**Part III — One automaton per language.**

13. Determinise the [Glushkov automaton](#def-b2-regular-languages-glushkov) of $e$ over $\{a, b, c\}$ , with the empty set as sink. How many states?
14. Apply Moore’s method to it. How many rounds, and how many classes at the end?
15. List the [residuals](#def-b2-regular-languages-residual) of $L(e)$ , and match them with the final classes.
16. Show that $(ab \mid b)^*c$ and $b^*(abb^*)^*c$ are equivalent.
17. Find a shortest word on which $(ab \mid b)^*c$ and $(a \mid b)^*bc$ differ.
18. The site stores compiled patterns in a cache. Why can two patterns that denote the same language share one entry, and how can a key be computed for it?

**Part IV — Backtracking against the automaton.**

19. In how many ways can $a^n$ be read as a sequence of matches of $(a \mid a)$ ?
20. Why does a backtracking engine try all of them on $a^n$ ? Relate this to the ratios of [Output 22.1](#out-b2-regular-languages-hook) .
21. From the hook’s last line, estimate how long the old site would take for 40 letters.
22. How many unions does the matcher make on $a^n$ with $(a \mid a)^*b$ ? Check with [Output 22.7](#out-b2-regular-languages-engine) .
23. How long does the matcher take for 40 letters, and for ten million?
24. State the result: from exponential to linear, backtracking’s time doubling with each $a$ , measured, against at most $(m + 1)n$ steps proved for the automaton.

**Solution of Problem 22.1.**

**1.** 4 end in Road, 5 in Row and 5 in Way: the 14 of the second line.

**2.** `[A-Z]` is an alternation of 26 letters, `[a-z]*` the star of 26 more, then the space and the four letters of Road: $26 + 26 + 1 + 4 = 57$.

**3.** `[A-Z][a-z]* (Lane|Avenue)`: the 6 lanes and the 3 avenues, 9 names.

**4.** Bridge Road, Bridge Way, Castle Road, Castle Row, Castle Way, Garden Lane, Garden Road, Station Row.

**5.** The alternation of the names, each written as a concatenation of its letters, denotes the set.

**6.** $\Sigma^* e \Sigma^*$, with $\Sigma$ written as a class of every character that can occur in a name.

**7.** $a_1 b_2 b_3 c_4$; $\mathrm{Null}$ is false, $\mathrm{First} = \{1, 3, 4\}$, $\mathrm{Last} = \{4\}$, $\mathrm{Follow}(1) = \{2\}$, $\mathrm{Follow}(2) = \mathrm{Follow}(3) = \{1, 3, 4\}$, $\mathrm{Follow}(4) =
\emptyset$.

**8.** 5 states, and $3 + 1 + 3 + 3 + 0 = 10$ transitions.

**9.** $\{0\} \xrightarrow{b} \{3\} \xrightarrow{a} \{1\} \xrightarrow{b} \{2\} \xrightarrow{b} \{3\}
\xrightarrow{c} \{4\}$: accepted, after 5 unions, one per letter, since each set holds one state.

**10.** The next set is masked by the positions holding the letter just read; equivalently, every transition into a position carries that position’s letter.

**11.** At most $(57 + 1) \times 12 = 696$ ([Proposition 22.19](#prop-b2-regular-languages-linear)).

**12.** A set of states is the bits of one 128-bit integer, state 0 included. With a vector of 64-bit words as the set, a union costs one OR per word, $\lceil (m + 1)/64 \rceil$ in all.

**13.** Six states: $\{0\}$; $\{1\}$, $\{3\}$ and $\{4\}$, reached by $a$, $b$ and $c$; $\{2\}$, reached from $\{1\}$ by $b$; and the sink $\emptyset$. $\{2\}$ and $\{3\}$ have the transitions of $\{0\}$.

**14.** Round 0: $\{4\}$ against the rest. Round 1: $\{0\}$, $\{2\}$ and $\{3\}$ go to $\{4\}$ on $c$, the others do not: three classes. Round 2: $\{1\}$ goes to $\{2\}$ on $b$, $\emptyset$ to $\emptyset$, which are now in different classes: four classes. Round 3 splits nothing. The [minimal automaton](#def-b2-regular-languages-minimal) has 4 states.

**15.** $L$ (by $\varepsilon$, $b$, $ab$, …), $bL$ (by $a$), $\{\varepsilon\}$ (by $c$) and $\emptyset$ (by $aa$, $cc$, …): the classes $\{\{0\}, \{2\}, \{3\}\}$, $\{1\}$, $\{4\}$ and $\emptyset$.

**16.** Both denote the words over $\{a, b\}$ in which every $a$ is immediately followed by a $b$, then $c$. Such a word is a block of $b$’s, then blocks starting with $ab$ followed by $b$’s, which is $b^*(abb^*)^*$; and every word of $b^*(abb^*)^*$ has each $a$ followed by $b$. The checker of [Exercise 22.9](#exo-b2-regular-languages-9) confirms it.

**17.** $c$: it is in the first language and lacks the $b$ before $c$ in the second. No shorter word differs, since $\varepsilon$, $a$ and $b$ are in neither.

**18.** By [Corollary 22.14](#cor-b2-regular-languages-unique-minimal), patterns with the same language have the same [minimal automaton](#def-b2-regular-languages-minimal) up to the names of the states. Renumbering its states in the order a breadth-first search from the start meets them, letters in a fixed order, makes the transition table and the [accepting states](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) a canonical key.

**19.** $2^n$: each $a$ is read by the left or the right branch.

**20.** Every way reaches the end of the text without a $b$ and fails; the engine then returns to its last choice and tries the other branch, so it tries all $2^n$. One more $a$ doubles the ways, and the measured ratios are close to 2.

**21.** About $6.6 \times 2^{13} \approx 54\,000$ s, 15 hours.

**22.** One union for the first letter, from $\{0\}$, then two for each later one, from $\{1, 2\}$: $2n - 1$, as the output shows (39 for 20 letters, 1 999 for 1 000).

**23.** About 7.3 ns a letter: some 0.3 $\mu$s for 40 letters, and 73 ms for ten million.

**24.** *From exponential to linear*: on $(a \mid a)^*b$ and $a^n$, the backtracking engine’s time doubles with each $a$, as measured, reaching 6.6 s at $n = 27$; the Glushkov matcher makes at most $(m + 1)n$ unions on any pattern of $m$ positions and any text of $n$ letters, as proved, here $2n - 1$, and answers ten million letters in 73 ms.
