Purpose: Exact string matching in time using only extra space — no failure-function array, no Z-array, nothing proportional to the pattern length.
Why constant space is hard
KMP is linear but stores an failure function. Boyer-Moore stores tables. Galil-Seiferas (1983) was the first algorithm to achieve linear time with genuinely constant auxiliary space, answering an open question of the era.
The Idea
Everything hinges on periodicity. Decompose the pattern as where is “highly periodic” and is short. Then:
- while scanning, if a mismatch occurs inside the periodic part , the period tells you exactly how far to shift — and the period is a single integer, not a table;
- the non-periodic prefix is short enough that naive re-scanning of it costs amortized.
The technical work is in computing this decomposition in time and space, which relies on the critical factorisation theorem: every string has a position where the local period equals the global period.
Complexity
- Time:
- Space: — a handful of integer variables
- Comparisons: in the original analysis
Related constant-space algorithms
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Galil-Seiferas | first of its kind, intricate | ||
| Crochemore-Perrin (“Two-Way”) | simpler; this is what glibc memmem and strstr use | ||
| Karp-Rabin | expected | randomised, not worst-case | |
| KMP | what you write in a contest |
The one that actually ships
If you ever need constant-space linear matching in real code, the Two-Way algorithm (Crochemore-Perrin, 1991) is the practical descendant — it is what the GNU C library implements. Galil-Seiferas is the proof of concept; Two-Way is the engineering.
Why it matters conceptually
The critical factorisation theorem and the “periodic tail / short head” decomposition it enables are genuinely useful ideas beyond this algorithm — they underpin the modern theory of runs in strings, Lyndon factorisation, and the linear-time detection of all maximal repetitions.
Variants / Use Cases
- Crochemore-Perrin Two-Way — the practical successor; see Crochemore
- Apostolico-Giancarlo — a different route to worst-case-linear Boyer-Moore
- String fundamentals — periods, borders, and the periodicity lemma
- Memory-constrained matching — embedded systems and streaming, where an table is not affordable