KMP Pattern Matching
HardThe prefix table records how much of the pattern is reusable after a mismatch, so the text pointer never moves backwards.
prefix functionlinear matching
TimeO(n + m)
SpaceO(m)
Inputtext | pattern
text
a
0b
1a
2b
3c
4a
5b
6c
7a
8b
9a
10b
11a
12b
13d
14pattern
a
0b
0a
0b
0d
0phasebuilding prefix tablematchesnone yet
lps
0
0
0
0
0
Pattern "ababd". First build the prefix table, which says how far to fall back on a mismatch.
1 / 29
build lps: longest proper prefix that is also a suffix
i = 0 (text), j = 0 (pattern)
while i < n:
if text[i] == pat[j]: i++, j++
else if j > 0: j = lps[j-1] // reuse the overlap
else: i++
if j == m: match at i - m
Why it matters
Naive matching restarts the text pointer after every mismatch, which is O(n*m).
Practise this
Keyboard
space play← → stepr restartctrl K search
Next visualiser
Trie (Prefix Tree)