KMP
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
KMP finds a pattern inside a long text without ever stepping backwards in the text. It first studies the pattern itself to learn how far it can skip after a mismatch, so the text is read just once from start to end.
Practical use cases
- Web app: Finding an error code in giant log files. An admin page lets engineers search a 2 GB log for "ERR_PAYMENT_TIMEOUT". A naive search restarts every time a partial match fails, which wastes work on repetitive logs. KMP keeps its place, reading each character once, so the search finishes in a single pass.
- Web app: Content scanner for uploaded files. A file-sharing site scans uploaded text for a forbidden signature string. KMP checks each uploaded file in one pass, so large uploads are checked without making the user wait. Users barely notice the scan, since it moves forward once and stops as soon as the pattern is found.
- System: DNA scanning and intrusion checks. Genome tools look for a short gene in billions of letters, and network monitors look for a suspicious byte pattern in traffic. KMP guarantees they never rewind, which keeps the scan steady.
The story: The Scroll That Never Rewinds
Grandpa Bhaskar owned a very long scroll of temple songs, and every evening Aarav had to find the line "ABABC" somewhere on it. His method was honest but clumsy: put a finger on a letter, compare, and if the match broke after four letters, lift the finger, go back, and start again one letter later. On long scrolls with many near-misses, Aarav walked over the same letters again and again.
"Stop," said Mira. "When you matched A-B-A-B and then failed, you already know what those four letters were. Why look at them again?" She noticed something neat: the end of "ABAB" is "AB", and that is also the start of the pattern! So the moment the next letter fails, the pattern can slide forward and still keep AB as already matched.
Before reading the scroll, Mira studied only the pattern and wrote a small fallback table: for every number of matched letters, how many can we keep after a failure? Now Aarav's finger moved forward only, never back, and the pattern did all the sliding. That table is the heart of KMP (Knuth-Morris-Pratt), a search that never re-reads the text.
How to spot this problem, and where you need it
You search for a pattern inside a long text, and on repetitive data your search keeps restarting from almost the beginning after each near-miss, making it slow.
Signs you need it
- You search a huge text, log, file or stream for one fixed pattern.
- Your own loop compares character by character and, on a mismatch, moves back to the next start position.
- Data such as "aaaaaaab" or repeated sequences makes the search crawl.
- The text arrives as a stream, so going back is not an option.
Where to use it in a project
- Log search and error-finding tools in admin panels.
- Upload scanners, signature checks and general text-matching utilities.
The solution
First build a small table for the pattern: for each position, how long a piece of the pattern's start also appears just before it. Then read the text once. When a mismatch occurs, use the table to slide the pattern forward by the right amount without moving back in the text, and carry on. Every text character is looked at once.
Payoff: Before: up to pattern length times text length comparisons. After: about one comparison per text character.
Explain it like I am 8
Imagine reading a long book to find a phrase. If you lose your place, a silly way is to go back and re-read. KMP is the smart way: you remember exactly how much of the phrase you already saw, so you only ever move forward and never re-read the same page.
How it works, step by step
- Study the pattern first. For each position, find the longest piece that is both a beginning and an ending of the pattern so far. Store it in the table
lps. - Keep a counter
j: how many pattern letters are matched right now. Walkiover the text, one letter at a time, forward only. - If
text[i] == pattern[j], it is a match:j++. - If it fails and
j > 0, setj = lps[j-1]and compare the same text letter again (the pattern slides, the text finger stays). - When
jreaches the pattern length you found one. Recordi - j + 1, then fall back withj = lps[j-1]to find overlapping matches.
The code in four languages
PHP
<?php
// Step 1: fallback table. lps[i] = longest piece of pattern[0..i] that is both a beginning and an ending.
function buildLps(string $p): array {
$lps = array_fill(0, strlen($p), 0);
$k = 0;
for ($i = 1; $i < strlen($p); $i++) {
while ($k > 0 && $p[$i] !== $p[$k]) $k = $lps[$k - 1]; // fall back
if ($p[$i] === $p[$k]) $k++;
$lps[$i] = $k;
}
return $lps;
}
// Step 2: walk the text once, forward only.
function kmp(string $t, string $p): array {
$lps = buildLps($p); $res = []; $j = 0;
for ($i = 0; $i < strlen($t); $i++) {
while ($j > 0 && $t[$i] !== $p[$j]) $j = $lps[$j - 1]; // slide pattern, keep text position
if ($t[$i] === $p[$j]) $j++;
if ($j === strlen($p)) { $res[] = $i - $j + 1; $j = $lps[$j - 1]; }
}
return $res;
}
echo implode(",", buildLps("ABABC")), "\n"; // 0,0,1,2,0
echo implode(",", kmp("ABABABCABABC", "ABABC")), "\n"; // 2,7JavaScript
// Step 1: fallback table. lps[i] = longest piece of pattern[0..i] that is both a beginning and an ending.
function buildLps(p) {
const lps = new Array(p.length).fill(0);
let k = 0;
for (let i = 1; i < p.length; i++) {
while (k > 0 && p[i] !== p[k]) k = lps[k - 1]; // fall back
if (p[i] === p[k]) k++;
lps[i] = k;
}
return lps;
}
// Step 2: walk the text once, forward only.
function kmp(t, p) {
const lps = buildLps(p), res = [];
let j = 0;
for (let i = 0; i < t.length; i++) {
while (j > 0 && t[i] !== p[j]) j = lps[j - 1]; // slide pattern, keep text position
if (t[i] === p[j]) j++;
if (j === p.length) { res.push(i - j + 1); j = lps[j - 1]; }
}
return res;
}
console.log(buildLps("ABABC").join(",")); // 0,0,1,2,0
console.log(kmp("ABABABCABABC", "ABABC").join(",")); // 2,7Java
import java.util.*;
public class Main {
// Step 1: fallback table. lps[i] = longest piece of pattern[0..i] that is both a beginning and an ending.
static int[] buildLps(String p) {
int[] lps = new int[p.length()];
int k = 0;
for (int i = 1; i < p.length(); i++) {
while (k > 0 && p.charAt(i) != p.charAt(k)) k = lps[k - 1]; // fall back
if (p.charAt(i) == p.charAt(k)) k++;
lps[i] = k;
}
return lps;
}
// Step 2: walk the text once, forward only.
static List<Integer> kmp(String t, String p) {
int[] lps = buildLps(p);
List<Integer> res = new ArrayList<>();
int j = 0;
for (int i = 0; i < t.length(); i++) {
while (j > 0 && t.charAt(i) != p.charAt(j)) j = lps[j - 1]; // slide pattern, keep text position
if (t.charAt(i) == p.charAt(j)) j++;
if (j == p.length()) { res.add(i - j + 1); j = lps[j - 1]; }
}
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(buildLps("ABABC"))); // [0, 0, 1, 2, 0]
System.out.println(kmp("ABABABCABABC", "ABABC")); // [2, 7]
}
}Go
package main
import "fmt"
// Step 1: fallback table. lps[i] = longest piece of pattern[0..i] that is both a beginning and an ending.
func buildLps(p string) []int {
lps := make([]int, len(p))
k := 0
for i := 1; i < len(p); i++ {
for k > 0 && p[i] != p[k] {
k = lps[k-1] // fall back
}
if p[i] == p[k] {
k++
}
lps[i] = k
}
return lps
}
// Step 2: walk the text once, forward only.
func kmp(t, p string) []int {
lps := buildLps(p)
var res []int
j := 0
for i := 0; i < len(t); i++ {
for j > 0 && t[i] != p[j] {
j = lps[j-1] // slide pattern, keep text position
}
if t[i] == p[j] {
j++
}
if j == len(p) {
res = append(res, i-j+1)
j = lps[j-1]
}
}
return res
}
func main() {
fmt.Println(buildLps("ABABC")) // [0 0 1 2 0]
fmt.Println(kmp("ABABABCABABC", "ABABC")) // [2 7]
}Time: O(n + m) · Extra space: O(m). The text finger only moves forward (n steps) and the fallback table costs m steps; the pattern slides back at most as often as it slid forward.
Watch out for
- Moving the text index back after a mismatch. That throws away the whole point of KMP.
- Using
lps[j]instead oflps[j-1]when falling back (the table is indexed by the last matched letter). - Forgetting to fall back after a full match, which would miss overlapping matches like "ABAB" inside "ABABAB".
Quick check
- What does the fallback (lps) table store?
- How many letters we can keep after a failure
- Where the pattern appears in the text
- The count of each letter
- After a mismatch with j > 0, what happens to the text position i?
- It goes back by j
- It stays; only j changes
- It restarts at 0
- Total running time of KMP?
- O(n × m)
- O(n + m)
- O(m²)