Algorithms · Visualized
String: KMP
String Matching
Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.
KMP speeds up string matching by never re-checking characters it has already matched. Time: O(n + m) average, O(n + m), where n = text length, m = pattern length — a huge improvement over naive search's O(n×m) worst; space: O(m) — the LPS array.
Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.
KMP (Knuth–Morris–Pratt)
String MatchingKMP speeds up string matching by never re-checking characters it has already matched. It precomputes a 'failure function' (also called the LPS array — longest proper prefix that is also a suffix) for the pattern, which tells it exactly how far to shift the pattern after a mismatch instead of restarting from scratch.
How KMP Works
- Build the LPS (longest prefix-suffix) array for the pattern: for each position, record the length of the longest proper prefix of the pattern (up to that position) that is also a suffix ending at that position.
- Use two pointers, one for the text and one for the pattern, both starting at 0.
- Compare characters at the text and pattern pointers; if they match, advance both pointers.
- If they mismatch, and the pattern pointer is not at the start, jump the pattern pointer back to the LPS value at the previous position (instead of restarting from 0) — the text pointer never moves backward.
- If the pattern pointer reaches the pattern's length, a match is found; continue searching for further matches using the LPS array to resume.
KMP Worked Example
Input: {text: ABABDABACDABABCABAB, pattern: ABABCABAB}
The LPS array for 'ABABCABAB' is [0,0,1,2,0,1,2,3,4]. As the search progresses through the text, a mismatch at position 4 (comparing 'D' in text to 'C' in pattern after matching 'ABAB') uses the LPS value to skip ahead intelligently rather than restarting — the text pointer never backtracks. The algorithm finds a full match of the pattern starting at index 10 in the text.
def kmp_search(text, pat):
lps = [0] * len(pat)
j = 0
for i in range(1, len(pat)):
while j > 0 and pat[i] != pat[j]:
j = lps[j - 1]
if pat[i] == pat[j]:
j += 1
lps[i] = j
out = []
j = 0
for i, c in enumerate(text):
while j > 0 and c != pat[j]:
j = lps[j - 1]
if c == pat[j]:
j += 1
if j == len(pat):
out.append(i - j + 1)
j = lps[j - 1]
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
KMP Time & Space Complexity
When to Use KMP
- Text editors and search tools needing fast, reliable substring search with guaranteed linear time.
- DNA sequence matching in bioinformatics, where patterns and texts can be very long.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.