KMP
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
KMP is a text search that never moves backward in the text. When a letter fails to match, it uses a small table built from the pattern to decide how much of the earlier match is still useful, then carries on. That makes searching large or streaming text predictable and fast.
Practical use cases
- Web app: Highlight a phrase in a huge document. A legal-document portal lets lawyers search 300-page PDFs converted to text. A naive search backs up after every near match, which stutters on repetitive clauses. KMP reads the text once from start to end, so the highlight and the match count appear quickly even for the biggest files.
- Web app: Scanning uploads for banned content. A forum lets users upload text files, and a moderation job must look for a forbidden phrase. The job reads the file as a stream, one chunk at a time, never going back. Because KMP only needs to remember a single number between chunks, a 500 MB upload is checked without loading it all into memory.
- System: Intrusion filters and log monitors. Network filters and log monitors look for a fixed signature in a never-ending flow of bytes. They cannot rewind a live stream. KMP fits because it moves forward only and keeps just one position in the pattern as its entire memory.
The story: The Station Announcer Who Never Looked Back
Every morning at the railway station, an announcer scanned a long line of train codes: ABABABC... looking for the code ABABC. His old method was nervous: whenever a letter failed, he walked back to the place where he began the attempt and started again. He re-read the same letters again and again, and the passengers waited.
A retired clerk named Mr. Knuth (everyone joked it was a famous name) whispered, "Use the rangoli chart, the LPS table. If you have already matched ABAB and the next letter fails, the chart says that the last AB you read is already the beginning of your pattern. Keep your eyes where they are. Just move the pattern over so those two letters line up with the beginning."
The announcer tried it. After A-B-A-B matched and the next A did not fit C, he did not look back at all: the pattern slid so its first AB sat under the AB he had just read, and he carried on and found ABABC at position 2. This never-look-back method is the Knuth-Morris-Pratt algorithm, KMP. Since the text pointer only ever moves forward, it is lightning fast even on nasty repetitive texts.
How to spot this problem, and where you need it
You must find one fixed phrase inside a very long text or a live stream, and a simple search that restarts after each mismatch is too slow or cannot go backward at all.
Signs you need it
- The input is a stream, socket or huge file read in pieces, so you cannot jump back to an earlier position cheaply.
- Your search is fine on normal text but slows to a crawl when the text and pattern are highly repetitive.
- A task says "find all occurrences of a pattern in a text" and the text can be millions of characters long.
Where to use it in a project
- Content-moderation scans of long uploads or chat transcripts for a known phrase.
- Custom find-and-replace or highlight features in browser editors working over large text.
- Log or packet monitors looking for a fixed signature as data arrives.
The solution
First build the prefix table of the pattern, which tells you for each position how much of the pattern is still matched after a failure. Then walk through the text once. On a match, advance both pointers; on a mismatch, move only the pattern pointer back using the table, never the text pointer. Report a hit whenever the whole pattern is matched.
Payoff: Before: a repetitive 1-million-character text took millions of wasted re-checks. After: one pass of about 1 million steps, and it works on streams too.
Explain it like I am 8
When you are reading and a word does not fit, you do not need to go back and re-read the whole page. You remember how much of what you just read could still be the start of your word, and continue from there. KMP is that memory.
How it works, step by step
- Build the LPS table for the pattern first (the rangoli chart from the last lesson).
- Walk the text with pointer
i, and keepjas the number of pattern letters matched so far. - If text[i] equals pattern[j], move both forward.
- If they differ and j > 0, set
j = lps[j - 1]and compare again; i stays where it is. If j is 0, just move i forward. - When j reaches the pattern length, you found a match at
i - m. To find more, setj = lps[j - 1]and continue.
The code in four languages
PHP
<?php
function lpsTable(string $p): array {
$m = strlen($p);
$lps = array_fill(0, $m, 0);
$k = 0;
for ($i = 1; $i < $m; $i++) {
while ($k > 0 && $p[$i] !== $p[$k]) { $k = $lps[$k - 1]; }
if ($p[$i] === $p[$k]) { $k++; }
$lps[$i] = $k;
}
return $lps;
}
// KMP: the text pointer i never goes backwards.
function kmpSearch(string $text, string $pattern): array {
$n = strlen($text);
$m = strlen($pattern);
if ($m === 0) { return []; }
$lps = lpsTable($pattern);
$found = [];
$j = 0; // pattern letters matched so far
for ($i = 0; $i < $n; $i++) {
while ($j > 0 && $text[$i] !== $pattern[$j]) {
$j = $lps[$j - 1]; // slide the pattern, keep i
}
if ($text[$i] === $pattern[$j]) {
$j++;
}
if ($j === $m) {
$found[] = $i - $m + 1; // match ends at i
$j = $lps[$j - 1]; // keep going for overlapping matches
}
}
return $found;
}
echo json_encode(kmpSearch("ABABABC", "ABABC")) . "\n"; // [2]
echo json_encode(kmpSearch("AAAAA", "AA")) . "\n"; // [0,1,2,3]JavaScript
function lpsTable(p) {
const m = p.length;
const lps = new Array(m).fill(0);
let k = 0;
for (let i = 1; i < m; i++) {
while (k > 0 && p[i] !== p[k]) { k = lps[k - 1]; }
if (p[i] === p[k]) { k++; }
lps[i] = k;
}
return lps;
}
// KMP: the text pointer i never goes backwards.
function kmpSearch(text, pattern) {
const n = text.length;
const m = pattern.length;
if (m === 0) { return []; }
const lps = lpsTable(pattern);
const found = [];
let j = 0; // pattern letters matched so far
for (let i = 0; i < n; i++) {
while (j > 0 && text[i] !== pattern[j]) {
j = lps[j - 1]; // slide the pattern, keep i
}
if (text[i] === pattern[j]) {
j++;
}
if (j === m) {
found.push(i - m + 1); // match ends at i
j = lps[j - 1]; // keep going for overlapping matches
}
}
return found;
}
console.log(JSON.stringify(kmpSearch('ABABABC', 'ABABC'))); // [2]
console.log(JSON.stringify(kmpSearch('AAAAA', 'AA'))); // [0,1,2,3]Java
import java.util.*;
public class Main {
static int[] lpsTable(String p) {
int m = p.length();
int[] lps = new int[m];
int k = 0;
for (int i = 1; i < m; i++) {
while (k > 0 && p.charAt(i) != p.charAt(k)) { k = lps[k - 1]; }
if (p.charAt(i) == p.charAt(k)) { k++; }
lps[i] = k;
}
return lps;
}
// KMP: the text pointer i never goes backwards.
static List<Integer> kmpSearch(String text, String pattern) {
int n = text.length();
int m = pattern.length();
List<Integer> found = new ArrayList<>();
if (m == 0) { return found; }
int[] lps = lpsTable(pattern);
int j = 0; // pattern letters matched so far
for (int i = 0; i < n; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j)) {
j = lps[j - 1]; // slide the pattern, keep i
}
if (text.charAt(i) == pattern.charAt(j)) {
j++;
}
if (j == m) {
found.add(i - m + 1); // match ends at i
j = lps[j - 1]; // keep going for overlapping matches
}
}
return found;
}
public static void main(String[] args) {
System.out.println(kmpSearch("ABABABC", "ABABC")); // [2]
System.out.println(kmpSearch("AAAAA", "AA")); // [0, 1, 2, 3]
}
}Go
package main
import "fmt"
func lpsTable(p string) []int {
m := len(p)
lps := make([]int, m)
k := 0
for i := 1; i < m; i++ {
for k > 0 && p[i] != p[k] {
k = lps[k-1]
}
if p[i] == p[k] {
k++
}
lps[i] = k
}
return lps
}
// kmpSearch finds every match; the text pointer i never goes backwards.
func kmpSearch(text, pattern string) []int {
n, m := len(text), len(pattern)
if m == 0 {
return nil
}
lps := lpsTable(pattern)
var found []int
j := 0 // pattern letters matched so far
for i := 0; i < n; i++ {
for j > 0 && text[i] != pattern[j] {
j = lps[j-1] // slide the pattern, keep i
}
if text[i] == pattern[j] {
j++
}
if j == m {
found = append(found, i-m+1) // match ends at i
j = lps[j-1] // keep going for overlapping matches
}
}
return found
}
func main() {
fmt.Println(kmpSearch("ABABABC", "ABABC")) // [2]
fmt.Println(kmpSearch("AAAAA", "AA")) // [0 1 2 3]
}Time: O(n + m) · Extra space: O(m). The text pointer only moves forward, and j can only fall as far as it rose, so the whole search is linear. The naive slide could cost O(n × m).
Watch out for
- Moving
ibackwards on a mismatch. The whole point of KMP is that only the pattern pointerjfalls back. - After a full match, setting
j = 0and missing overlapping matches such as "AA" in "AAAA". Usej = lps[j - 1]. - Building the table wrongly (it must be of the pattern, not the text).
Quick check
- On a mismatch (with j > 0), which pointer moves back?
- i, the text pointer
- j, the pattern pointer
- Both of them
- What is the time cost of KMP?
- O(n + m)
- O(n × m)
- O(n²)
- What does the LPS table let KMP avoid?
- Reading the pattern
- Sorting the text
- Re-reading text letters it has already matched