Algorithms · Visualized

String: KMP

String Matching

Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.

KMP speeds up string matching by never re-checking characters it has already matched. Time: O(n + m) average, O(n + m), where n = text length, m = pattern length — a huge improvement over naive search's O(n×m) worst; space: O(m) — the LPS array.

Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.

KMP (Knuth–Morris–Pratt)

String Matching

KMP speeds up string matching by never re-checking characters it has already matched. It precomputes a 'failure function' (also called the LPS array — longest proper prefix that is also a suffix) for the pattern, which tells it exactly how far to shift the pattern after a mismatch instead of restarting from scratch.

How KMP Works

  1. Build the LPS (longest prefix-suffix) array for the pattern: for each position, record the length of the longest proper prefix of the pattern (up to that position) that is also a suffix ending at that position.
  2. Use two pointers, one for the text and one for the pattern, both starting at 0.
  3. Compare characters at the text and pattern pointers; if they match, advance both pointers.
  4. If they mismatch, and the pattern pointer is not at the start, jump the pattern pointer back to the LPS value at the previous position (instead of restarting from 0) — the text pointer never moves backward.
  5. If the pattern pointer reaches the pattern's length, a match is found; continue searching for further matches using the LPS array to resume.

KMP Worked Example

Input: {text: ABABDABACDABABCABAB, pattern: ABABCABAB}

The LPS array for 'ABABCABAB' is [0,0,1,2,0,1,2,3,4]. As the search progresses through the text, a mismatch at position 4 (comparing 'D' in text to 'C' in pattern after matching 'ABAB') uses the LPS value to skip ahead intelligently rather than restarting — the text pointer never backtracks. The algorithm finds a full match of the pattern starting at index 10 in the text.

String: KMPO(n + m)
Precompute the prefix function so mismatches never re-scan matched text.
t
A
B
A
B
D
A
B
A
C
D
A
B
A
B
C
A
B
A
B
0123456789101112131415161718
p
A
B
A
B
C
A
B
A
B
012345678
Step 1 / 39
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
KMP: phase 1 — build the prefix table lps (longest proper prefix that is also a suffix).
Python · String Matching in Code
def kmp_search(text, pat):
    lps = [0] * len(pat)
    j = 0
    for i in range(1, len(pat)):
        while j > 0 and pat[i] != pat[j]:
            j = lps[j - 1]
        if pat[i] == pat[j]:
            j += 1
        lps[i] = j
    out = []
    j = 0
    for i, c in enumerate(text):
        while j > 0 and c != pat[j]:
            j = lps[j - 1]
        if c == pat[j]:
            j += 1
        if j == len(pat):
            out.append(i - j + 1)
            j = lps[j - 1]
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

KMP Time & Space Complexity

BestO(n + m)
AverageO(n + m)
WorstO(n + m), where n = text length, m = pattern length — a huge improvement over naive search's O(n×m)
SpaceO(m) — the LPS array

When to Use KMP

  • Text editors and search tools needing fast, reliable substring search with guaranteed linear time.
  • DNA sequence matching in bioinformatics, where patterns and texts can be very long.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.