The KMP algorithm
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)The Knuth-Morris-Pratt (KMP) algorithm searches patterns in text in linear time by ensuring the text pointer never rewinds. We start with naive backtracking to see why re-checking characters is wasteful, and then construct the LPS failure table.
Why Naive Backtracking Is Wasteful
The KMP algorithm searches for a pattern in text in O(n + m) by using a prefix table to avoid re-checking characters after a mismatch.
When naive search finds a mismatch at text character i and pattern character j, it resets the text pointer back to i - j + 1 and the pattern pointer to 0.
Why is this wasteful? We already compared and matched j characters! That matched segment is not random noise—we know its exact characters and their internal structure.
If the matched prefix contains a suffix that matches a prefix of the pattern, we do not need to restart from pattern index 0. We can slide the pattern forward to that matching boundary and resume comparisons without rewinding the text pointer.
Building the Longest Prefix Suffix (LPS) Table
The core of KMP is the Longest Prefix Suffix (LPS) array. For every prefix pattern[0..i], lps[i] stores the length of the longest proper prefix that is also a suffix of pattern[0..i].
Step by step
Step 1 of 7
| Row | 0: a | 1: b | 2: a | 3: c | 4: a | 5: b | 6: a |
|---|---|---|---|---|---|---|---|
| Pattern | a | b | a | c | a | b | a |
| LPS | 0 |
Example 1 · Building the LPS table: O(M) time, O(M) space
public class LpsTableDemo { public static int[] buildLps(String p) { int m = p.length(); int[] lps = new int[m]; int len = 0, i = 1; while (i < m) { if (p.charAt(i) == p.charAt(len)) lps[i++] = ++len; else { if (len > 0) len = lps[len - 1]; else lps[i++] = 0; } } return lps; }
public static void main(String[] args) { String p = "abacaba"; int[] lps = buildLps(p); for (int i = 0; i < p.length(); i++) { System.out.println("p[" + i + "]='" + p.charAt(i) + "' -> lps=" + lps[i]); } }}p[0]='a' -> lps=0 p[1]='b' -> lps=0 p[2]='a' -> lps=1 p[3]='c' -> lps=0 p[4]='a' -> lps=1 p[5]='b' -> lps=2 p[6]='a' -> lps=3
What this code does
- LPS[2]=1 because 'a' matches prefix 'a'.
- LPS[5]=2 because 'ab' matches prefix 'ab'.
- LPS[6]=3 because 'aba' matches prefix 'aba'.
We build LPS using two pointers: len tracks the length of the previous longest prefix suffix, and i scans the pattern from index 1 to M - 1. If pattern[i] == pattern[len], we increment len, set lps[i] = len, and advance i. If they mismatch and len > 0, we do not reset len to 0. We fall back to len = lps[len - 1], reusing smaller precomputed prefix symmetries. If len == 0, we set lps[i] = 0 and advance i. The entire table builds in strictly O(M) time.
Searching Text in Linear O(N + M) Time
With the LPS table ready, we scan text with pointer i and pattern with pointer j. As long as text[i] == pattern[j], both pointers advance. When j reaches M, an occurrence is found at index i - M, and we reset j = lps[j - 1] to find further matches.
If a mismatch occurs at text[i] != pattern[j]: if j > 0, we set j = lps[j - 1] without moving i. If j == 0, we simply advance i.
Crucially, text pointer i never moves backwards. Because i only increments and j falls back along precomputed LPS boundaries, the search executes in strictly O(N) comparisons, totaling O(N + M) time.
KMP search: ABABC in ABABABC
Step 1 of 8
- j
- 0
- A
- B
- A
- B
- C
- 0
- 0
- 1
- 2
- 0
Example 2 · Pattern search by restarting, brute force: O(N · M) time, O(1) space
import java.util.ArrayList;import java.util.List;
public class NaiveVersusKmpDemo { static List<Integer> search(String text, String pattern) { List<Integer> found = new ArrayList<>(); for (int i = 0; i + pattern.length() <= text.length(); i++) { int j = 0; while (j < pattern.length() && text.charAt(i + j) == pattern.charAt(j)) j++; if (j == pattern.length()) found.add(i); // full match; on a mismatch we restart at i + 1 } return found; }
public static void main(String[] args) { String text = "ABABDABACDABABCABAB"; String pattern = "ABABCABAB"; System.out.println("Pattern found at index: " + search(text, pattern)); }}Pattern found at index: [10]
What this code does
- For every start i it compares pattern letters with text letters until one differs.
- After a mismatch the next attempt starts at i + 1, so letters already matched are read again.
- It finds the same match at index 10 as KMP.
Example 3 · KMP search, optimal: O(N + M) time, O(M) space
import java.util.ArrayList;import java.util.List;
public class KmpSearchDemo { public static int[] buildLps(String pattern) { int m = pattern.length(); int[] lps = new int[m]; int len = 0, i = 1;
while (i < m) { if (pattern.charAt(i) == pattern.charAt(len)) { len++; lps[i] = len; i++; } else { if (len > 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } return lps; }
public static List<Integer> search(String text, String pattern) { List<Integer> matches = new ArrayList<>(); int n = text.length(), m = pattern.length(); if (m == 0 || m > n) return matches;
int[] lps = buildLps(pattern); int i = 0, j = 0;
while (i < n) { if (text.charAt(i) == pattern.charAt(j)) { i++; j++; } if (j == m) { matches.add(i - j); j = lps[j - 1]; } else if (i < n && text.charAt(i) != pattern.charAt(j)) { if (j > 0) { j = lps[j - 1]; } else { i++; } } } return matches; }
public static void main(String[] args) { String text = "ABABDABACDABABCABAB"; String pattern = "ABABCABAB"; System.out.println("Pattern found at index: " + search(text, pattern)); }}Pattern found at index: [10]
What this code does
- buildLps constructs the failure table in O(M) time without backtracks.
- Text pointer i moves strictly forward, ensuring linear O(N) search.
- Finds match at index 10 without re-scanning previously verified characters.
- Why faster: after a mismatch the LPS table says how much of the matched text can be kept, so the text pointer never moves back.
Applications: Shortest Palindrome and Periodic Strings
KMP solves classic string challenges beyond simple matching. For example, to find the shortest palindrome formed by adding characters in front of string S, we want the longest palindromic prefix of S.
Example 4 · Shortest palindrome by testing every prefix, brute force: O(N²) time, O(N) space
public class PalindromeBruteDemo { static boolean isPalindrome(String s, int end) { for (int i = 0, j = end - 1; i < j; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; }
static String shortestPalindrome(String s) { for (int end = s.length(); end >= 0; end--) { // longest palindromic prefix first if (isPalindrome(s, end)) { String rest = s.substring(end); return new StringBuilder(rest).reverse() + s; } } return s; }
public static void main(String[] args) { System.out.println("Shortest palindrome ('aacecaaa'): " + shortestPalindrome("aacecaaa")); System.out.println("Shortest palindrome ('abcd'): " + shortestPalindrome("abcd")); }}Shortest palindrome ('aacecaaa'): aaacecaaa
Shortest palindrome ('abcd'): dcbabcdWhat this code does
- isPalindrome() compares letters from both ends of a prefix.
- The first prefix that passes is the longest; the rest of the string is reversed and put in front.
- Each prefix check costs O(N), and up to N prefixes are tried, so the total is O(N²).
Example 5 · Shortest palindrome with the LPS table, optimal: O(N) time, O(N) space
public class ShortestPalindromeDemo { private static int[] buildLps(String s) { int m = s.length(); int[] lps = new int[m]; int len = 0, i = 1; while (i < m) { if (s.charAt(i) == s.charAt(len)) lps[i++] = ++len; else { if (len > 0) len = lps[len - 1]; else lps[i++] = 0; } } return lps; }
public static String shortestPalindrome(String s) { if (s == null || s.length() <= 1) return s;
String rev = new StringBuilder(s).reverse().toString(); String temp = s + "#" + rev; int[] lps = buildLps(temp);
int longestPalPrefix = lps[temp.length() - 1]; String suffixToAdd = s.substring(longestPalPrefix); return new StringBuilder(suffixToAdd).reverse().toString() + s; }
public static void main(String[] args) { System.out.println("Shortest palindrome ('aacecaaa'): " + shortestPalindrome("aacecaaa")); System.out.println("Shortest palindrome ('abcd'): " + shortestPalindrome("abcd")); }}Shortest palindrome ('aacecaaa'): aaacecaaa
Shortest palindrome ('abcd'): dcbabcdWhat this code does
- Creates combined string s + '#' + rev(s) to find longest palindromic prefix.
- LPS of the combined string gives length of the longest palindromic prefix.
- Reverses remaining suffix and prepends to s in O(N) time.
- Why faster: one LPS pass finds the longest palindromic prefix, instead of re-checking every prefix from scratch.
We construct combined string temp = S + '#' + reverse(S) and compute its LPS table. The final entry lps[temp.length - 1] gives the exact length of the longest palindromic prefix of S! Similarly, a string of length N has a repeating periodic unit if and only if lps[N - 1] > 0 and N % (N - lps[N - 1]) == 0, with the smallest repeating unit having length N - lps[N - 1].
Order of execution
Order the shortest palindrome steps
Tap the steps in the order the KMP method runs them.
Next step
Check your understanding
10 quick questions