Regular expressions

O(n · m)·O(m) space
2 to 3: cc4 to 5: aa3 to 4: εε6 to 7: tt5 to 6: εε0 to 2: εε7 to 1: εε8 to 9: dd10 to 11: oo9 to 10: εε12 to 13: gg11 to 12: εε0 to 8: εε13 to 1: εεq0q0q1q1q2q2q3q3q4q4q5q5q6q6q7q7q8q8q9q9q10q10q11q11q12q12q13q13
  • Active

Pattern "cat|dog" against "dog", 3 characters; nothing consumed yet. 3 states active to start.

Pattern "cat|dog" against "dog", 3 characters; nothing consumed yet. 3 states active to start.
  1. 1start in the epsilon-closure of the NFA’s start state
  2. 2read the next character of the text
  3. 3move every active state along a transition that matches it
  4. 4take the epsilon-closure of wherever that lands
  5. 5finished: the text matches if the accepting state is active
Characters read
1

Complexity

BestO(n · m)
AverageO(n · m)
WorstO(n · m)
Extra spaceO(m)
n · m at n=3 predicts 21; this run took 1.

Thompson's construction (NFA)

Thompson's construction turns a parsed pattern into a nondeterministic finite automaton (an NFA) by composing a small, fixed wiring diagram per operator — concatenation chains two fragments, alternation forks and rejoins them, each quantifier adds a loop or a bypass. Simulating it does not try one possibility and back out of it if it fails; instead it tracks the whole *set* of states the automaton could be in, and advances every one of them together on each input character.

When it is the right choice

This is the shape of engine behind every regex implementation that promises linear-time matching regardless of the pattern — RE2 and Rust's `regex` crate both work this way, specifically to make catastrophic backtracking structurally impossible rather than merely unlikely. The cost is expressiveness: back-references and lookaround cannot be compiled to a finite automaton at all, which is why those engines refuse them outright rather than silently falling back to something slower.

How it works

Worth noticing

Cost

Best
O(n · m)
Average
O(n · m)
Worst
O(n · m)
Extra space
O(m)

The pattern is capped at 14 characters and the text at 24, both pedagogical rather than technical: every extra pattern character can roughly double the automaton this tool draws, and this tool draws one frame per character, so the real limit in practice is legibility rather than time.

Worth comparing

All regex algorithms