KMP and the LPS array

Video lessonComing soon

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:

p0a1p2a3p4a5y6a7p0a1p2a3y4a5
Start 0: 'papa' matches, then 'p' ≠ 'y' at index 4

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:

Sliding 'papa' under itself
p0a1p2a3p0a1p2a3
Slide 1: 'p' sits under 'a'. No fit

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:

lps[i] = length of the longest proper prefix of p[0..i] that is also its 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":

ip[0..i]at both endslps[i]
0pnothing0
1panothing0
2papp1
3papapa2
4papaynothing0
5papayanothing0

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:

  • i walks through the pattern from index 1.
  • j is the length of the prefix that matches so far, ending just before i. So p[j] is the character that prefix needs next.

At each i, we do three things:

  1. While j > 0 and p[i] differs from p[j], j falls to lps[j - 1].
  2. If p[i] equals p[j], j goes up by 1.
  3. 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:

Building lps for 'papaya'
p0a1p2a3y4a500012345ji
i = 1: 'a' ≠ 'p' and j = 0, so lps[1] = 0
ip[i]j beforep[j]what happenslps[i]
1a0pdiffer, j is 00
2p0pequal, j = 11
3a1aequal, j = 22
4y2pdiffer, j = lps[1] = 0; y ≠ p0
5a0pdiffer, j is 00

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.

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:

  • j goes up by at most 1 per character of the text. Over the whole search, it goes up at most n times.
  • Each fall lowers j by at least 1, because lps[j - 1] is less than j. And j never 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⁹:

Naive, O(n·m)2.5 × 10⁹KMP, O(n + m)2.5 × 10⁵about 1 second
10⁵ 'a's and a pattern of 5 × 10⁴, on a scale where each mark is ten times the last

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:

p0a1p2a3p4a5y6a7papapapa
'papa' at 0 and at 2. The two share 'pa'

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 + '#' + t also 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] > 0 and m % (m - lps[m - 1]) == 0. "papapa" has lps[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 of s.

8 Mistakes, and when to use it

  • lps[j] instead of lps[j - 1]. j counts matched characters, so the last one is at j - 1. On "papapaya", the fall at i = 4 reads lps[4] = 0 instead of lps[3] = 2, and the search returns −1.
  • if instead of while. One fall is not always enough. On "aaa" in "aabaa", the 'b' makes j fall from 2 to 1, and 'b' still differs from 'a'. An if stops there with j = 1, as if the 'b' had matched. The search then reports a match at 2, where the text says "baa".
  • j = 0 after 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 what strStr expects.

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.

After a mismatch, ask what the part that already matched tells you. The answer is often where the next match can start, without reading the text again.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.