KMP and the LPS array
1 A search that starts over
Someone typed "papapaya", and we want to find the word "papaya" in it. The text t has n characters and the pattern p has m. Here n = 8 and m = 6.
The first search most of us write tries every start, and compares character by character until one differs:
Next, it tries start 1. It goes back to t[1] and reads 'a', 'p' and 'a' again, though it has just read them.
This rereading makes it slow. Take a text of 10⁵ 'a's, and a pattern of 5 × 10⁴ 'a's with one 'b' at the end. Every start matches all the 'a's and then fails on the 'b'. That is around 2.5 × 10⁹ character checks. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE). In general, the naive search is O(n·m).
KMP, named after Knuth, Morris and Pratt, does the same job in O(n + m). It never goes back in the text.
2 What the mismatch tells us
The failed try has already told us that t[0..3] is "papa". A new start has to agree with it:
- Start 1. The pattern's first three letters, "pap", would sit on "apa". They differ, so start 1 fails.
- Start 2. The pattern's first two letters, "pa", would sit on "pa". They agree, so start 2 can still work.
Both checks compare "papa" with a copy of itself, slid to the right. The part of the copy that hangs past the end does not matter yet, because the text there is still unread:
The first slide that fits leaves an overlap of 2, because "papa" starts and ends with "pa". So we never go back. We stay at t[4], carry on as if 2 characters of the pattern had matched, and compare t[4] with p[2].
3 The LPS array
The slide used only the pattern, never the text. So we work it out for every prefix once, before the search. These overlaps fill the LPS array. LPS stands for the longest proper prefix that is also a suffix:
"Proper" means shorter than p[0..i] itself. A copy slid 0 places always fits, and it tells us nothing.
In the sliding picture, lps[i] is the overlap at the first slide that fits. A smaller slide leaves a longer overlap, so the first fit gives the longest one. For "papaya":
| i | p[0..i] | at both ends | lps[i] |
|---|---|---|---|
| 0 | p | nothing | 0 |
| 1 | pa | nothing | 0 |
| 2 | pap | p | 1 |
| 3 | papa | pa | 2 |
| 4 | papay | nothing | 0 |
| 5 | papaya | nothing | 0 |
The number from section 2 is lps[3] = 2. When "papa" has matched and the next character fails, the search carries on with 2 characters matched.
4 Building the LPS array in one pass
Sliding a copy for every prefix would cost O(m²). We build the array in one pass instead, with two pointers on the pattern:
iwalks through the pattern from index 1.jis the length of the prefix that matches so far, ending just beforei. Sop[j]is the character that prefix needs next.
At each i, we do three things:
- While
j > 0andp[i]differs fromp[j],jfalls tolps[j - 1]. - If
p[i]equalsp[j],jgoes up by 1. - We set
lps[i] = j.
The fall is the slide from section 2. p[0..j-1] matches the end of what we have read, but p[j] does not fit. The next candidate is the longest part at both ends of p[0..j-1]. That is lps[j - 1], already written, because j - 1 is less than i.
The top row is the pattern and the bottom row is lps. Blue marks equal characters and each new value, and orange marks characters that differ:
| i | p[i] | j before | p[j] | what happens | lps[i] |
|---|---|---|---|---|---|
| 1 | a | 0 | p | differ, j is 0 | 0 |
| 2 | p | 0 | p | equal, j = 1 | 1 |
| 3 | a | 1 | a | equal, j = 2 | 2 |
| 4 | y | 2 | p | differ, j = lps[1] = 0; y ≠ p | 0 |
| 5 | a | 0 | p | differ, j is 0 | 0 |
Row 4 has the fall. "pa" could not grow with a 'y', and "pa" has no shorter part at both ends, so j fell straight to 0. On other patterns, j can fall several times at one i, so step 1 is a loop.
5 The search
The search runs the same loop over the text. i walks through the text, and j counts the pattern characters matched just before t[i]:
- While
j > 0andt[i]differs fromp[j],jfalls tolps[j - 1]. - If
t[i]equalsp[j],jgoes up by 1. - If
jreaches m, the pattern ends ati, so it starts ati - m + 1.
i only moves forward. On a mismatch only j moves, and a smaller j slides the pattern right. Blue is matched. Orange is known to match without reading it again:
| i | t[i] | j before | p[j] | what happens | j after |
|---|---|---|---|---|---|
| 0 | p | 0 | p | equal | 1 |
| 1 | a | 1 | a | equal | 2 |
| 2 | p | 2 | p | equal | 3 |
| 3 | a | 3 | a | equal | 4 |
| 4 | p | 4 | y | differ, j = lps[3] = 2; p = p[2] | 3 |
| 5 | a | 3 | a | equal | 4 |
| 6 | y | 4 | y | equal | 5 |
| 7 | a | 5 | a | equal, j = m: found at 7 − 6 + 1 = 2 | 6 |
Row 4 is the whole trick. The naive search went back to t[1]. KMP stays on t[4] and compares it with p[2], because lps[3] says "pa" is already in place.
Here is the search as LeetCode's strStr, which returns the first start, or −1:
buildLps is the same loop, run on the pattern against itself. It starts i at 1 and writes lps[i] at every step.
C++
One charAt per step. Keeping haystack.charAt(i) in c saves reading it twice and keeps the lines short.
Bytes. haystack[i] is a byte, which is one character for English letters.
i + 1 - m, not i - m + 1. A usize cannot go below 0. When the match starts at 0, i is m − 1, and i - m would go below 0 before the + 1.
6 Why it is O(n + m)
A while inside a for looks like it could cost O(n·m). It cannot, because of how j moves:
jgoes up by at most 1 per character of the text. Over the whole search, it goes up at most n times.- Each fall lowers
jby at least 1, becauselps[j - 1]is less thanj. Andjnever goes below 0.
So j cannot fall more times than it rose: at most n falls in the whole search, however they bunch together. The search makes at most about 2n comparisons, and the build at most about 2m, by the same argument. A cost counted over the whole run like this, instead of per step, is amortised.
On the bad case from section 1, KMP takes around 2.5 × 10⁵ steps instead of 2.5 × 10⁹:
The LPS array takes O(m) extra space.
7 Every match, and other uses
To find every match, we do not stop at a full match. j falls to lps[m - 1], as on a mismatch, so the next match can share characters with this one. "papa" is in "papapaya" twice:
It reuses buildLps from above:
The LPS array also answers questions about one string on its own:
- Pattern and text joined. The LPS of
p + '#' + talso finds the matches. The '#' is in neither string, so no value passes m, and each m marks the end of a match. For "papaya#papapaya", the last value is 6. - The longest part at both ends of a whole string. It is
lps[m - 1]. - A string made of one block repeated. A string of length m is one when
lps[m - 1] > 0andm % (m - lps[m - 1]) == 0. "papapa" haslps[5] = 4, so the block is 6 − 4 = 2 long: "pa", three times. - The shortest palindrome. The last LPS value of
s + '#' + reverse(s)is the length of the longest palindrome at the start ofs.
8 Mistakes, and when to use it
lps[j]instead oflps[j - 1].jcounts matched characters, so the last one is atj - 1. On "papapaya", the fall ati = 4readslps[4] = 0instead oflps[3] = 2, and the search returns −1.ifinstead ofwhile. One fall is not always enough. On "aaa" in "aabaa", the 'b' makesjfall from 2 to 1, and 'b' still differs from 'a'. Anifstops there withj = 1, as if the 'b' had matched. The search then reports a match at 2, where the text says "baa".j = 0after a full match. Finding every "papa" in "papapaya" then gives only 0. The match at 2 is lost, because it shares "pa" with the first.- An empty pattern. With m = 0, the first comparison reads
p[0], past the end. Return 0 before the loop, which is whatstrStrexpects.
The sign is a pattern to find inside a longer string, where checking every start is too slow. A question about how a string's start and end overlap, such as its longest part at both ends or a block repeated, often needs only the LPS array.
The next lesson, on the Z-function, builds a different array over the same joined string. The one after it, on rolling hashes, compares a window of the text with the pattern by one number instead of character by character.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.