Search Pattern (KMP Algorithm)
Search Pattern (KMP Algorithm) is a GFG problem (Hard). Given a text txt and a pattern pat, both lowercase, return the 0-based start index of every occurrence of pat in txt, or an empty list if there is none.
- Occurrences may overlap, and each one must be reported.
- Both strings can be 10⁵ letters long. Checking every start against the whole pattern is O(n·m), which is too slow on inputs like
"aaa…ab", so the expected time is O(n + m) with O(m) extra space.
- 1 <= pat.length <= txt.length <= 10⁵
- Both strings use lowercase English letters
Intuition
When a match breaks after j letters, those j text letters are already known: they equal pat[0..j−1]. So where the next copy could start depends only on the pattern, and can be worked out before the text is read.
- The LPS array (longest prefix suffix):
lps[i]is the longest proper prefix ofpat[0..i]that is also its suffix, called a border. - The fallback: on a mismatch after
jmatched letters, keeplps[j − 1]of them matched and try the same text letter again.
The text pointer never moves back, which is what makes KMP pattern search linear.
Exact search for one fixed pattern, with a demand for linear time and nothing allowed to re-read the text, points to KMP. The same table also answers "longest prefix that is also a suffix" and "is this string a repeat of a shorter block?".
Approach
Before reading on, search for "abab" in "abaababab" by hand. When the fourth letter fails at text spot 3, which of the three letters you just matched could still be the start of a copy?
Build the LPS array on the pattern
Set lps[0] = 0 and keep k, the length of the current border. For each i from 1, compare pat[i] with pat[k]. A match means the border grows to k + 1, because the old border plus one equal letter is still a prefix and a suffix.
Fall back through shorter borders
While k > 0 and pat[i] != pat[k], set k = lps[k - 1]. Any shorter border of pat[0..i-1] is also a border of the current border, so the table already lists the next candidate, from longest to shortest.
Scan the text once
Keep j, the number of pattern letters matched so far. For each text letter, fall back with j = lps[j - 1] while it differs from pat[j], then add 1 to j if it matches. The text index only ever moves forward.
Record a match and keep going
When j == m, the pattern ends at text index i, so append i - m + 1. Then set j = lps[m - 1] rather than 0, because the end of this copy may already be the start of the next one.
Code in Python, C++ and Java
Common pitfalls
Resetting to 0 after a full match
if j == m:
res.append(i - m + 1)
j = 0if j == m:
res.append(i - m + 1)
j = lps[j - 1]Overlapping copies are lost. For pat = "aa" and txt = "aaa" the reset version returns [0], because the second a is forgotten. Keeping the border of 1 gives [0, 1].
Falling back only once
if j > 0 and c != pat[j]:
j = lps[j - 1]while j > 0 and c != pat[j]:
j = lps[j - 1]One fallback can still leave a mismatch. For pat = "aaa" and txt = "aabaa", the b drops j from 2 to 1 and stops there, so the run wrongly survives the b and a false match at 2 is reported. The correct answer is empty.
Edge cases
The table is just [0], so after each hit j falls back to 0 and every position holding that letter is reported.
"abcd"Every entry is 0, so each mismatch restarts the pattern at the current text letter. It still never re-reads earlier text.
Complexity
j by 1 and every fallback lowers it by at least 1. Since j never goes below 0, the fallbacks in the scan add up to at most n, and the same argument bounds the table build by m.KMP against the Z function and brute force
Which tool to reach for when one fixed pattern has to be found in a text.
| Approach | Work done up front | Worst-case time | Memory | Pick it when |
|---|---|---|---|---|
| KMP (this page) | LPS table on pat | O(n + m) | O(m) | the text is huge or can be read only once, left to right |
| Z function | Z values on the joined string | O(n + m) | O(n + m) | a shorter loop matters more than memory |
| Character-by-character scan | none | O(n·m) | O(1) | only the first index is needed and inputs are small |
Search Pattern (KMP Algorithm) FAQ
Why does the LPS array use proper prefixes only?
The whole string is always both a prefix and a suffix of itself, so allowing it would make every entry i + 1. Falling back to that length would never shorten the match, and the search would loop forever on the first mismatch.
Is KMP faster than a language's built-in find in practice?
Often not for ordinary text. Built-in search uses tuned loops and heuristics that are fast on average. KMP's value is the worst-case guarantee: inputs like "aaaa…ab" that make a naive scan quadratic stay linear.
What if there are many patterns to search for at once?
Running KMP once per pattern costs a full text pass each time. Aho-Corasick generalises the LPS fallback to a trie of all patterns, so one pass over the text finds every pattern.