Skip to content
Efficient

KMP Algorithm

Linear time pattern matching using the prefix function.

Time Complexity
O(N + M)
Space Complexity
O(M)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 42
Text
A
0
B
1
A
2
B
3
D
4
A
5
B
6
A
7
C
8
D
9
A
10
B
11
A
12
B
13
C
14
A
15
B
16
A
17
B
18
Pattern
A
0
B
1
A
2
B
3
C
4
A
5
B
6
A
7
B
8
KMP Prefix Jump Table
0
0
1
2
0
1
2
3
4
Process Description

Prefix function computed. Starting pattern matching phase.

Technical Guide

Knuth-Morris-Pratt (KMP) is the first linear-time string matching algorithm discovered. It uses the precomputed Prefix Function to ensure that the pointer in the main text *never* moves backward. When a mismatch occurs, the algorithm looks up the Prefix Table to see what's the next best alignment, effectively 'jumping' the pattern across the text.

Logical Phases

  • 1
    Computing the Prefix Table (Pi) for the pattern in O(M).
  • 2
    Scanning the text once with pointer 'i' and pattern with pointer 'q'.
  • 3
    On mismatch, setting q = pi[q-1] instead of resetting i.
  • 4
    Completing the search in exactly O(N + M) time.

Implementation

while (q > 0 && p[q] !== t[i]) q = pi[q-1];

Expert Pitfalls

Off-by-one errors when indexing the Pi table after a mismatch.