Pattern Matching: KMP & Rabin-Karp

Data Structures & Algorithms · Strings, Bits & Patterns · Advanced · 30 min

Find every place a pattern appears in a text in linear time, using KMP's border table (LPS) or Rabin-Karp's rolling hash.

Sliding a stencil along a line of letters. A careless reader moves the stencil one step and re-reads everything; a smart reader remembers what they already saw and jumps the stencil forward.

The idea in everyday words

You are hunting for the word "ABABC" in a long book. You have matched "ABAB" and then see a D. A beginner moves one letter to the right and starts re-reading. A smart reader notices that the last "AB" just read could be the beginning of the word, keeps it, and carries on from the letter they were already looking at. They never go back in the book. That is KMP.

Brute force, and where it wastes time

Text of length n, pattern of length m. Try every start position s, and compare letter by letter until a mismatch.

def brute_search(text, p):
    found = []
    for s in range(len(text) - len(p) + 1):
        j = 0
        while j < len(p) and text[s + j] == p[j]:
            j += 1
        if j == len(p):
            found.append(s)
    return found

print(brute_search("abracadabra", "abra"))   # [0, 7]

Usually fast, but look at text AAAAAAAAAB and pattern AAAAB. At every start we match four A's, fail on the B, slide by one, and re-read the same A's again. That is O(n · m).

The waste: after a mismatch we already know what the last few text letters are (they matched the pattern). Brute force throws that knowledge away.

The LPS table: what can we keep after a mismatch?

A border of a string is a part that is both a proper prefix and a suffix. "ABAB" has the border "AB" (it starts and ends with AB). "ABCD" has none.

lps[i] = length of the longest border of p[0..i] (LPS = "longest prefix that is also a suffix").

i 0 1 2 3 4 5 6 7 8
p A B A B C A B A B
lps 0 0 1 2 0 1 2 3 4

Why it helps: suppose we matched j letters and then fail. The text's last j letters equal p[0..j-1]. Its longest border has length lps[j-1], so the pattern's first lps[j-1] letters already line up with the text. Slide the pattern so they overlap and keep going: j = lps[j-1]. Any smaller slide would require a longer border, which does not exist, so no match is skipped.

Building it is the pattern matching against itself, in O(m):

def build_lps(p):
    lps, k = [0] * len(p), 0       # k = length of the current border
    for i in range(1, len(p)):
        while k > 0 and p[i] != p[k]:
            k = lps[k - 1]         # fall back to a shorter border
        if p[i] == p[k]:
            k += 1                 # the border grows by one letter
        lps[i] = k
    return lps

print(build_lps("ABABCABAB"))   # [0, 0, 1, 2, 0, 1, 2, 3, 4]

KMP search: the text pointer never goes back

Scan the text with index i. Keep j = how many pattern letters are matched right now.

  1. While j > 0 and text[i] != p[j]: fall back, j = lps[j-1].
  2. If text[i] == p[j]: j += 1.
  3. If j == m: a full match ends at i, starting at i - m + 1. Record it and set j = lps[m-1], so overlapping matches are still found.
def kmp_search(text, p):
    lps = [0] * len(p)
    k = 0
    for i in range(1, len(p)):
        while k > 0 and p[i] != p[k]:
            k = lps[k - 1]
        if p[i] == p[k]:
            k += 1
        lps[i] = k
    found, j = [], 0
    for i, ch in enumerate(text):
        while j > 0 and ch != p[j]:
            j = lps[j - 1]
        if ch == p[j]:
            j += 1
        if j == len(p):
            found.append(i - j + 1)
            j = lps[j - 1]
    return found

print(kmp_search("ABABDABACDABABCABAB", "ABABCABAB"))   # [10]
print(kmp_search("aaaa", "aa"))                          # [0, 1, 2]

Why O(n + m): i only moves forward (n steps). Each fall-back lowers j, and j only ever rose by one per step, so all the fall-backs together cost at most n more. The table costs O(m).

Rabin-Karp: compare fingerprints

Idea: turn each window of m letters into a number (a hash). Compare numbers, which is O(1), and only compare letters when the numbers agree.

The trick is the rolling hash: the next window's hash comes from the previous one in O(1). Think of digits: the window "123" is 123. Slide to "234": drop the leading 1, shift, add 4: (123 - 1·100) · 10 + 4 = 234.

For letters use a base (like 256) and keep numbers small with a large prime modulus:

def rabin_karp(text, p, base=256, mod=1_000_000_007):
    n, m = len(text), len(p)
    if m > n:
        return []
    high = pow(base, m - 1, mod)          # weight of the leading letter
    hp = ht = 0
    for k in range(m):
        hp = (hp * base + ord(p[k])) % mod
        ht = (ht * base + ord(text[k])) % mod
    found = []
    for s in range(n - m + 1):
        if hp == ht and text[s:s + m] == p:   # double-check: hashes can collide
            found.append(s)
        if s + m < n:                          # roll: drop text[s], add text[s+m]
            ht = ((ht - ord(text[s]) * high) * base + ord(text[s + m])) % mod
    return found

print(rabin_karp("abracadabra", "abra"))   # [0, 7]
  • Average O(n + m). Worst case O(n · m) if many hashes collide (rare with a good prime).
  • Always verify the letters when hashes match: two different windows can share a hash (a collision).
  • Where it shines: many patterns of the same length at once, or problems about "repeated substrings of length L" (Repeated DNA Sequences, Longest Duplicate Substring with binary search on L).

Which one should you use?

Method Time Best for
Built-in (text.find, in, indexOf) fast in practice real code, and fine in interviews unless asked to implement
Brute force O(n · m) tiny inputs, or as the first idea you say out loud
KMP O(n + m) guaranteed a single pattern, worst-case guarantees, periodic strings
Rabin-Karp O(n + m) average many patterns, substring hashing, "repeated substring" problems

The LPS table is useful on its own: "Shortest Palindrome" and "Repeated Substring Pattern" are solved by reading one LPS value. For example, a string s is a repetition of a smaller block exactly when n % (n - lps[n-1]) == 0 and lps[n-1] > 0.

Step by step

  1. Build the LPS table:

    Pattern "ABAB": lps = [0, 0, 1, 2]. After matching "ABAB", the last "AB" is also the first "AB".

  2. Match at index 0:

    Text "ABABCABAB". i = 0..3 all match, so j reaches 4 = m. Record a match at 0.

  3. Keep the border:

    Set j = lps[3] = 2. We do not re-read: text[2..3] = "AB" already lines up with the pattern's "AB".

  4. Mismatch on 'C':

    i = 4: 'C' vs p[2] = 'A' fails. Fall back j = lps[1] = 0. 'C' vs p[0] = 'A' fails too, so move on with j = 0.

  5. Match at index 5:

    i = 5..8 read "ABAB" and j climbs to 4 again. Record a match at 8 - 4 + 1 = 5.

  6. Result:

    Matches [0, 5]. i moved forward 9 times and never went back.

Code example

def build_lps(p):
    lps, k = [0] * len(p), 0
    for i in range(1, len(p)):
        while k > 0 and p[i] != p[k]:
            k = lps[k - 1]
        if p[i] == p[k]:
            k += 1
        lps[i] = k
    return lps

def kmp_search(text, p):
    lps, j, found = build_lps(p), 0, []
    for i, ch in enumerate(text):
        while j > 0 and ch != p[j]:
            j = lps[j - 1]
        if ch == p[j]:
            j += 1
        if j == len(p):
            found.append(i - j + 1)
            j = lps[j - 1]
    return found

def rabin_karp(text, p, base=256, mod=1_000_000_007):
    n, m = len(text), len(p)
    if m > n:
        return []
    high = pow(base, m - 1, mod)
    hp = ht = 0
    for k in range(m):
        hp = (hp * base + ord(p[k])) % mod
        ht = (ht * base + ord(text[k])) % mod
    found = []
    for s in range(n - m + 1):
        if hp == ht and text[s:s + m] == p:
            found.append(s)
        if s + m < n:
            ht = ((ht - ord(text[s]) * high) * base + ord(text[s + m])) % mod
    return found

print("lps:", build_lps("ABABCABAB"))
print("KMP:", kmp_search("ABABDABACDABABCABAB", "ABABCABAB"))
print("Rabin-Karp:", rabin_karp("abracadabra", "abra"))

Complexity

  • Time: O(n + m) for KMP: O(m) to build the table, and the text pointer only moves forward. Rabin-Karp is O(n + m) on average, O(n · m) in the worst case.
  • Space: O(m) for the LPS table (Rabin-Karp needs O(1) extra besides the output)

Interview tips

  • Open with the brute force and its O(n · m) worst case, then explain what information it throws away.

  • Explain lps with a concrete pattern like "ABABC" before writing code; interviewers care that you know why the jump is safe.

  • Mention Rabin-Karp for multi-pattern search and for "repeated substring" problems, and the need to verify on hash matches.

  • If allowed, say you would use the built-in in production; then implement KMP when asked.

Challenge: Find All Occurrences

Return a list of every index where pattern starts inside text, in increasing order. Overlapping occurrences count. pattern is never empty.

Write the matching yourself with KMP and aim for O(n + m). For this challenge, slicing and built-in search (find, index, startswith, indexOf, includes, regular expressions) are switched off, and one large test checks the speed.

Example: find_all("abababca", "aba") → [0, 2]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Strings, Bits & Patterns

Previous: Bit Manipulation · Next: Which Pattern When? The Interview Pattern Map