Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 14  /  KMP

The Non- Backtracker.

Search a pattern in a text the naive way and every mismatch throws away everything you learned. KMP never re-reads a character: it studies the pattern's own repeats first, then on a mismatch slides the pattern forward — matching any text in O(n + m).

THE GIST · 20 SECONDS

KMP finds a pattern in a text without backtracking the text pointer. First it builds the LPS table — for each spot in the pattern, the longest prefix that's also a suffix. Then it scans with two pointers: on a match, both advance; on a mismatch, it sets j = lps[j−1] to slide the pattern to its next possible alignment, reusing what already matched. Total work: O(n + m).

  • Patternwhat you're searching for
  • LPSprefix that's also a suffix
  • Mismatchjump, don't restart
  • No rewindtext pointer only moves →

Hit Step to build the failure table, then scan — or Play and watch the pattern slide to the match without ever re-reading the text.

UNDER THE HOOD

What you just played, written down

The whole trick is the failure table. It records how much of the pattern's start is echoed at each point, so a mismatch never forces you back to square one.

How KMP thinks — four moves

  1. Study the pattern first. Build lps[k] = length of the longest proper prefix of the pattern that is also a suffix ending at k.
  2. Scan with two pointers. i over the text, j over the pattern. On a match, advance both.
  3. On a full match, record it. When j reaches the pattern's length, you found an occurrence at i − j. Set j = lps[j−1] to keep looking for overlaps.
  4. On a mismatch, jump — don't restart. If j > 0, set j = lps[j−1]; the text pointer i never moves back. If j = 0, advance i.
WHY THE TEXT POINTER NEVER REWINDS

The already-matched characters are the front of the pattern. The LPS table says how many of them still match after sliding, so KMP resumes mid-pattern instead of re-reading the text — the source of its linear time.

The whole thing in code

def build_lps(p):
    lps = [0] * len(p); length = 0; i = 1
    while i < len(p):
        if p[i] == p[length]:
            length += 1; lps[i] = length; i += 1
        elif length > 0:
            length = lps[length - 1]   # fall back
        else:
            lps[i] = 0; i += 1
    return lps

def kmp(text, pat):
    lps = build_lps(pat); res = []; i = j = 0
    while i < len(text):
        if text[i] == pat[j]:
            i += 1; j += 1
            if j == len(pat):
                res.append(i - j); j = lps[j - 1]
        elif j > 0: j = lps[j - 1]   # jump, no rewind
        else: i += 1
    return res
TIMEO(n + m)build m + scan n
SPACEO(m)the LPS table
THE LPS BUILD IS KMP ON ITSELF

Building the table matches the pattern against itself with the very same two-pointer, fall-back-on-mismatch logic. Learn one loop and you've learned both halves of the algorithm.

⚠ Proper prefix only

"Proper" prefix means not the whole string. Without that, lps[k] would trivially equal k+1 and the fall-back would never make progress. The prefix must be strictly shorter than the substring.

↔ Its cousins

Z-algorithm and the prefix function compute closely related tables. Rabin-Karp uses hashing; Boyer-Moore skips from the end of the pattern and is often faster in practice.

★ Where it's used

grep-style search, DNA/protein search, intrusion detection scanning traffic for signatures, plagiarism checks, and any guaranteed-linear substring search.

The picture: where the fall-back goes

texttry 1try 2lpsABABDABABCABABABABCABABC ≠ D: j 4 → 2 → 0ABABCABAB001201234The text index never moves back: 16 comparisons, one match at 5
The page’s own text and pattern. The first alignment matches ABAB and fails on D against C. KMP does not slide by one: the table says the matched ABAB ends in a 2-character prefix AB, so it resumes at j = 2, fails again, drops to j = 0, and only then moves on. The next alignment starts at text index 5 and runs clean to the end.

Worked example, step by step

Search ABABDABABCABAB (14 characters) for ABABCABAB (9). Step one is the table: lps = [0, 0, 1, 2, 0, 1, 2, 3, 4]. Then the scan, where each row is one character comparison between T[i] and P[j]. Rows 0 to 3 are four plain matches and are summarised in the first row.

CompareijT[i] vs P[j]ResultNext j
1–40–30–3A B A B vs A B A Bfour matches4
544D vs Cmismatch2
642D vs Amismatch0
740D vs Amismatch0 (advance i)
850A vs Amatch1
961B vs Bmatch2
1072A vs Amatch3
1183B vs Bmatch4
1294C vs Cmatch5
13105A vs Amatch6
14116B vs Bmatch7
15127A vs Amatch8
16138B vs Bmatch9, full match; j = lps[8] = 4

The three mismatch rows share i = 4: the text pointer stayed put while j fell from 4 to 2 to 0. That is the whole trick, and it is why the total is 16 comparisons. The naive scan, which restarts every alignment from scratch, needs 20 on the same input. After the match is recorded j becomes lps[8] = 4, not 0, so a second occurrence that overlaps the first would be found without re-reading anything. Here the text ends, so the answer is the single index [5].

Complexity and trade-offs

CaseTimeSpaceWhy
KMPO(n + m)O(m)The table costs O(m); the scan advances either i or, on a fall-back, shrinks j, so it makes at most 2n comparisons.
Naive restartO(n · m) worst caseO(1)On A×20 against AAAAB it makes 80 comparisons; KMP makes 36. On ordinary text the gap is small.
Rabin-Karp (rolling hash)O(n + m) expectedO(1)Fast on average but a collision forces a verify, and the worst case degrades to O(n · m).
Boyer-MooreO(n / m) best, O(n · m) worst for the simple formO(m + alphabet)Skips from the pattern end and is often fastest in practice, but has no simple linear worst-case guarantee.
Suffix arrayO(m log n) per queryO(n)Pays to index the text once, then answers many different patterns.

KMP’s guarantee is about the worst case, not the typical one. If the text is huge and the pattern changes every time, a good find from a standard library may beat it. If the pattern is fixed, you can stream the text one character at a time through KMP and keep only j, which makes it a natural fit for data you cannot hold in memory.

Common mistakes

  • Resetting j to 0 after a full match

    Writing j = 0 instead of j = lps[j-1] loses overlapping matches. Searching AAAA for AA should give [0,1,2]; the bug returns [0,2].

  • Resetting j to 0 on every mismatch

    That is the naive algorithm with the text pointer stuck. Searching AAAB for AAB should give [1]; zeroing j returns [] and misses the match.

  • Falling back by one instead of through the table

    In the table build, k = k - 1 in place of k = lps[k-1] gives wrong entries. For AABAABAAAB the correct table is [0,1,0,1,2,3,4,5,2,3] and the buggy one is [0,1,0,1,2,3,4,5,5,6].

  • Forgetting to advance i when j is 0

    On a mismatch with j == 0 there is nothing to fall back to, so i must move on. Leave that branch out and the loop never ends on the first character that does not match.

  • Not handling the empty pattern

    With m = 0, P[0] is read on the first step and raises an out-of-range error (or reads garbage in C). Decide up front what an empty pattern means, usually a match at every position, and return before the loop.

Where this shows up

  • Streaming search

    Because the text pointer never moves back, KMP can consume a stream byte by byte holding only the pattern, its table and one integer. Scanning a log or network feed for a fixed marker is the textbook case.

  • Repeats and periods

    The last table entry gives the shortest period of a string: if m − lps[m−1] divides m, the pattern is that block repeated. For ABABCABAB the value is 9 − 4 = 5, which does not divide 9, so there is no repeating block.

  • Building block for other automata

    The failure links are the same idea Aho-Corasick generalises from one pattern to a whole dictionary, and the prefix function itself is the core of the Z-algorithm family of problems.

  • Interview problems

    “Find the index of the first occurrence”, “repeated substring pattern” and “shortest palindrome” all reduce to the prefix table, often with a small trick such as searching P + "#" + T.

SOLVE IT YOURSELF

Solve it: find all matches

This one is yours to write — in Python or TypeScript, running for real in your browser. Build the LPS table and scan the text, returning every start index where the pattern occurs. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement kmp_search(text, pat): return a list of every start index where pat occurs in text (overlaps included). Use the KMP LPS table so the text pointer never moves backward.

HINTS — 4 IDEAS
  1. Build lps: match the pattern against itself; on a mismatch fall back to lps[length-1].
  2. Scan with pointers i (text) and j (pattern). On a match, advance both.
  3. When j == len(pat), record i - j, then set j = lps[j-1] to allow overlaps.
  4. On a mismatch: if j > 0, set j = lps[j-1] (don't touch i); else advance i.
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. What does the LPS table store for each position of the pattern?

    Answer: The length of the longest proper prefix that is also a suffix ending there — lps[k] is the length of the longest proper prefix of the pattern that also appears as a suffix ending at k. It captures the pattern’s internal repeats so KMP can reuse them on a mismatch.

  2. On a mismatch with j > 0, what does KMP do?

    Answer: Set j = lps[j-1] and leave i where it is — It slides the pattern by setting j = lps[j-1], aligning the longest matching prefix, and crucially never moves the text pointer i backward — that is what keeps it linear.

  3. What is KMP’s time complexity?

    Answer: O(n + m) — Building the LPS table is O(m) and scanning the text is O(n) because i never rewinds and j only falls back a bounded number of times overall — O(n + m) total.

FAQ

KMP, answered

What is the KMP algorithm?

A string-matching algorithm that finds a pattern in a text in O(n + m) by precomputing the pattern's LPS failure table and scanning the text without ever backtracking the text pointer.

What is the LPS table?

For each position in the pattern, the length of the longest proper prefix that is also a suffix ending there. It encodes the pattern's internal repeats so a mismatch can reuse the part that already matched.

Why is it faster than naive search?

Naive search re-compares from scratch on every mismatch — up to O(n·m). KMP never re-reads a text character; it jumps the pattern using the LPS table, for O(n + m) total.

How does it handle a mismatch?

If text[i] != pat[j] and j > 0, set j = lps[j-1] — sliding the pattern to its next viable alignment without moving i. If j == 0, just advance i.

Where is KMP used?

grep-style search, DNA/protein search, intrusion detection, plagiarism checks — anywhere a fixed pattern must be found in a long stream with guaranteed linear time.

RESULT

—

Next → store many patterns at once in a tree of characters and match them together — that's a Trie, and its multi-pattern cousin the Aho-Corasick automaton.

Finished this one? 0 / 99 Algorithms done
NextSlide the Z-Box: Z-Algorithm Next on the “Matching without backing up” ladder · rung 3 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms