Skip to content

KMP: linear-time substring search with LPS

AdvancedAsked sometimesCoding roundCodingStrings
Asked atGoogleMicrosoftAdobe
#strings#kmp#pattern-matching#lps

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

KMP is the classic proof that string matching does not have to be quadratic, and it separates candidates who can define a prefix function from those who can actually run it. Interviewers watch whether you build the LPS table and apply the fallback j = lps[j - 1] correctly, and whether you can explain why the fallback preserves every still-possible match. It is also a calibration question: strong candidates derive the failure function instead of reciting it.

Mental model

Every time you match j characters of the pattern and then fail, the last j characters of the text already equal pattern[0..j-1]. Instead of restarting the pattern at zero and re-reading text, look at the largest proper prefix of those matched characters that is also a suffix - that is lps[j-1] - and resume from there. The text pointer i only ever moves forward, so matching costs O(n) and building the table costs O(m).

Step-by-step solution

  1. Step 1: Naive search rechecks everything

    The naive algorithm slides the pattern one position at a time and compares characters from scratch at every alignment. When a partial match fails near the end, all of that matching work is thrown away and the text pointer is rewritten to the next start position. The animation runs pattern ABABAC against ABABAABABAC. At alignment 0 the first five characters match, then C fails against A, so alignment 1 restarts from scratch and immediately fails; alignment 2 matches three characters and fails again. The text positions around the failure were already examined, but the algorithm has no memory of what they contained. In the worst case - think pattern AAAAAB over a long run of A characters - each alignment compares almost m characters, giving O(n times m) character comparisons. The animation's comparison counter makes the repeated work visible: the same text characters are tested several times across adjacent alignments.

  2. Step 2: The prefix that is a suffix

    Define lps[i] as the length of the longest proper prefix of pattern[0..i] that is also a suffix of pattern[0..i]. Proper means strictly shorter than the substring itself, so lps describes an overlap you can reuse rather than the whole match. For ABABA the longest such overlap is ABA, length 3; for ABAB it is AB, length 2; for a fresh character with no overlap it is 0. The table exists because of a fact about mismatches: when you have just matched j characters, the text you consumed ends with pattern[0..j-1]. If the next character breaks the match, any alignment that could still succeed must start inside that window, and the longest prefix that is also a suffix is exactly the largest chunk of progress that survives. The animation highlights those overlapping chunks - the same characters serving as both prefix and suffix - before the next step turns them into table entries.

  3. Step 3: Build the LPS table

    The construction code is a tiny matching problem against the pattern itself. Keep a candidate length len and a scan index i, both starting small. If pattern[i] extends the current candidate, the overlap grows: increment len, write lps[i], advance i. On a mismatch, do not reset len to zero - that is the whole subtlety. Instead fall back to lps[len-1], the longest overlap that still fits, and retry the same i. Only when len is zero do you write zero and advance. The animation builds the table for ABABAC: three matches grow run lengths 1, 2, then 3; the final C mismatches and triggers two fallbacks, 3 to 1 to 0, before recording lps[5] = 0. Each index either advances i or shrinks len, and len never exceeds i, so the total work is linear in the pattern length.

  4. Step 4: Match without moving backwards

    The search loop keeps one text pointer i and one pattern pointer j. On a character match both advance; when j reaches the pattern length, the match starts at i - j. On a mismatch the algorithm consults the table: if j is greater than zero, set j = lps[j - 1] and retry the same i; only when j is zero does i advance. That is the invariant that makes KMP linear - i is monotone, so the text is read once. The animation follows ABABAABABAC against ABABAC. At i = 5 the text has matched ABABA and fails on C; j falls back 5 to 3 to 1 to 0, and only then does i move to 6, where a fresh run matches all the way to i = 10 and returns 5. Notice the mismatch chain repeats a decision the naive algorithm would redo from scratch at several alignments.

  5. Step 5: Why the fallback is correct

    The failure function is correct because of what the failed attempt leaves behind. When text[i] mismatches with j matched characters, the text's last j characters already equal pattern[0..j-1] - that is guaranteed by the loop's own history, not by an assumption. A shift of k requires the pattern's first j−k characters to equal its last j−k characters — i.e. a border of length j−k. The longest border length is lps[j-1], so the smallest valid shift is j − lps[j-1] — no alignment is skipped — which is exactly j ← lps[j-1], the alignment that keeps the longest still-possible overlap and discards only alignments that cannot match. The animation makes the chain concrete: the window ABABA has the suffix ABA equal to the prefix ABA, so after falling back the A that ended the window is already covered again. Every fallback is like that, which is why KMP never misses a match - and why the text pointer never rewinds.

Edge cases & traps

  • Empty pattern: return 0 before touching lps[j - 1], or the loop indexes the pattern out of bounds; decide whether an empty needle matches at position 0.
  • Pattern longer than the text: the scan ends and returns -1; never allocate or scan past text.length.
  • A single-character pattern or repeated characters: proper means strictly shorter, so lps[0] is always 0 and fallback chains can be long - the amortized bound still holds.
  • Patterns like AAAAAB over a long run of A characters produce deep fallback chains; they are linear in total because every fallback was paid for by an earlier match.
  • Unicode text: JavaScript indexing walks UTF-16 code units, so patterns with surrogate pairs can match half a code point - iterate code points when the alphabet needs it.

Follow-up questions

Go deeper: Explore the String Algorithms visualizer