Regular expressions

O(n)·O(2^m) states, in the worst case space
0 to 1: cc0 to 2: dd1 to 3: aa2 to 4: oo3 to 5: tt4 to 6: ggD0D0D1D1D2D2D3D3D4D4D5D5D6D6
  • Active

Pattern "cat|dog" against "dog", 3 characters; nothing consumed yet. The DFA has 7 states, built before any input is read.

Pattern "cat|dog" against "dog", 3 characters; nothing consumed yet. The DFA has 7 states, built before any input is read.
  1. 1build the DFA once, before reading any input
  2. 2read the next character of the text
  3. 3move the single active state along its one transition for that character
  4. 4if there is no such transition, the text cannot match from here
  5. 5finished: the text matches if the active state is accepting
Characters read
1

Complexity

BestO(n)
AverageO(n)
WorstO(n)
Extra spaceO(2^m) states, in the worst case
n at n=3 predicts 3; this run took 1.

Subset construction (DFA)

Subset construction takes the NFA Thompson's construction builds and produces a deterministic finite automaton (a DFA) whose own states are *sets* of NFA states — the exact sets the NFA simulation would have been tracking live, enumerated once up front instead. Two NFA states that are always active together become indistinguishable from the DFA's point of view and collapse into one of its states.

When it is the right choice

The right choice whenever the same pattern will be matched against many inputs: the expensive part — working out which combinations of NFA states are reachable — is paid once, at compile time, and every match after that is a single table lookup per character. It is the wrong choice when the pattern changes on every call and is only used once, since building the DFA can itself take time proportional to the number of states it discovers, and in the worst case that is exponential in the pattern's size (though not in the input's).

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n)
Worst
O(n)
Extra space
O(2^m) states, in the worst case

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