String Matching

How to find a pattern in a text with the naive scan, KMP and Rabin-Karp, how they differ, and what interviewers ask about them.

17 minLesson 1 of 3
On this page
  1. The naive scan
  2. KMP
  3. Rabin-Karp
  4. Choosing between the methods
  5. What interviewers ask about string matching

String matching means finding every position where a pattern of length m appears inside a text of length n. It is the operation behind a Find box, a search through DNA, and the indexOf or str.find calls in every language. This lesson covers three ways to do it: the naive scan, Knuth-Morris-Pratt (KMP), and Rabin-Karp.

The naive scan

Place the pattern at position 0 of the text and compare character by character. If every character matches, record the position. If any character differs, move the pattern one position to the right and start comparing from its first character again. The trace below searches for HHTHHH in HHTHHTHHH.

Naive search for HHTHHHUse the arrows or ← → keys
for start from 0 to n - m:  k = 0  while k < m and text[start + k] == p[k]:    k = k + 1  if k == m: record start
  1. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0Hstart
    1H
    2T
    3H
    4H
    5H
    6
    7
    8
    comparisons
    6

    1At start 0, five characters match and then the text character T meets the pattern character H. That is 6 comparisons so far.

  2. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0
    1Hstart
    2H
    3T
    4H
    5H
    6H
    7
    8
    comparisons
    8

    2The pattern slides to start 1 and the comparison begins again. Text positions 1 and 2 are read a second time, and T against H fails.

  3. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0
    1
    2Hstart
    3H
    4T
    5H
    6H
    7H
    8
    comparisons
    9

    3At start 2, T against H fails on the first comparison.

  4. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0
    1
    2
    3Hstart
    4H
    5T
    6H
    7H
    8H
    comparisons
    15
    found at
    3

    4At start 3 all six characters match, so the pattern is found at index 3 after 15 comparisons on a 9-character text.

1 / 4

Each of the roughly n start positions can cost up to m comparisons, so the worst case is O(n·m). A text of a million H characters searched for HHHHHHHHHT is the standard bad case, because every start matches nine characters before failing on the last one. On ordinary text the first comparison usually fails, so the naive scan runs close to O(n) in practice, which is why it is acceptable when the inputs are small.

Naive search
function naiveSearch(text, pattern) {
  if (pattern.length === 0) return [];
  const found = [];
  for (let start = 0; start + pattern.length <= text.length; start++) {
    let k = 0;
    while (k < pattern.length && text[start + k] === pattern[k]) k++;
    if (k === pattern.length) found.push(start);
  }
  return found;
}
 
naiveSearch("HHTHHTHHH", "HHTHHH"); // [3]
def naive_search(text, pattern):
    if not pattern:
        return []
    found = []
    for start in range(len(text) - len(pattern) + 1):
        k = 0
        while k < len(pattern) and text[start + k] == pattern[k]:
            k += 1
        if k == len(pattern):
            found.append(start)
    return found
 
naive_search("HHTHHTHHH", "HHTHHH")  # [3]

KMP

The naive scan throws away what it learned. At the first mismatch in the trace, the text characters HHTHH were already known to match the start of the pattern. KMP uses that knowledge and never compares a text character twice. The suffix HH of the matched part is also a prefix of the pattern, so the pattern can slide until its first two characters sit under those two text characters, and the comparison continues from pattern position 2.

text H H T H H T H H H before H H T H H H after H H T H H H next comparison
The pattern slides right so that its first two characters, HH, sit under the HH at the end of the matched part of the text.

A border of a string is a proper prefix that is also a suffix. The string HHTHH has two borders, H and HH. KMP slides by the longest border, because that is the smallest slide that cannot skip a real match. Borders depend only on the pattern, so KMP computes them once, before searching, in a failure table. The entry table[i] is the length of the longest border of the first i + 1 characters of the pattern.

Building the failure table

The table is built left to right with a variable k that holds the current border length. For each new character, check whether it extends the current border, meaning pattern[i] equals pattern[k]. If it does, k grows by one. If it does not, the next shorter border that could still be extended is the border of the current border, which is table[k − 1], so k falls back to that value and the check repeats.

Failure table for HHTHHHUse the arrows or ← → keys
table[0] = 0, k = 0for i from 1 to m - 1:  while k > 0 and p[i] != p[k]:    k = table[k - 1]  if p[i] == p[k]: k = k + 1  table[i] = k
  1. pattern
    0Hk
    1H
    2T
    3H
    4H
    5H
    table
    00
    1
    2
    3
    4
    5
    k
    0

    1A single character has no border, so table[0] = 0 and k = 0.

  2. pattern
    0Hk
    1Hi
    2T
    3H
    4H
    5H
    table
    00
    11
    2
    3
    4
    5
    k
    1

    2p[1] and p[0] are both H, so the border grows to length 1.

  3. pattern
    0H
    1Hk
    2Ti
    3H
    4H
    5H
    table
    00
    11
    2
    3
    4
    5
    k
    0

    3p[2] is T but p[1] is H, so the border cannot grow and k falls back to table[0] = 0.

  4. pattern
    0Hk
    1H
    2Ti
    3H
    4H
    5H
    table
    00
    11
    20
    3
    4
    5
    k
    0

    4T does not match p[0], which is H, so table[2] = 0.

  5. pattern
    0Hk
    1H
    2T
    3Hi
    4H
    5H
    table
    00
    11
    20
    31
    4
    5
    k
    1

    5p[3] matches p[0], so the border length is 1.

  6. pattern
    0H
    1Hk
    2T
    3H
    4Hi
    5H
    table
    00
    11
    20
    31
    42
    5
    k
    2

    6p[4] matches p[1], so the border grows to length 2, which is HH.

  7. pattern
    0H
    1H
    2Tk
    3H
    4H
    5Hi
    table
    00
    11
    20
    31
    42
    5
    k
    1

    7p[5] is H but p[2] is T, so k falls back to the border of HH, which is table[1] = 1.

  8. pattern
    0H
    1Hk
    2T
    3H
    4H
    5Hi
    table
    00
    11
    20
    31
    42
    52
    k
    2

    8H matches p[1], so k becomes 2 and table[5] = 2. The finished table is [0, 1, 0, 1, 2, 2].

1 / 8

Searching with the table

The search has the same shape. The variable j counts how many pattern characters are currently matched. When the text character equals pattern[j], j grows. On a mismatch, j falls back to table[j − 1] and the same text character is compared again, so the text index only ever moves forward.

KMP search for HHTHHHUse the arrows or ← → keys
j = 0for i from 0 to n - 1:  while j > 0 and text[i] != p[j]:    j = table[j - 1]  if text[i] == p[j]: j = j + 1  if j == m: record i - m + 1
  1. text
    0Hi
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0H
    1H
    2T
    3H
    4H
    5H
    6
    7
    8
    j
    0
    comparisons
    0

    1No characters have been matched yet.

  2. text
    0H
    1H
    2T
    3H
    4Hi
    5T
    6H
    7H
    8H
    pattern
    0H
    1H
    2T
    3H
    4H
    5H
    6
    7
    8
    j
    5
    comparisons
    5

    2Text positions 0 to 4 match the pattern, one comparison each, so j is 5.

  3. text
    0H
    1H
    2T
    3H
    4H
    5Ti
    6H
    7H
    8H
    pattern
    0H
    1H
    2T
    3H
    4H
    5H
    6
    7
    8
    j
    5
    comparisons
    6

    3At i = 5 the text character T meets the pattern character H, which is a mismatch.

  4. text
    0H
    1H
    2T
    3H
    4H
    5Ti
    6H
    7H
    8H
    pattern
    0
    1
    2
    3H
    4H
    5T
    6H
    7H
    8H
    j
    2
    comparisons
    6

    4The search falls back to j = table[4] = 2. The pattern is now effectively at start 3, and i stays at 5.

  5. text
    0H
    1H
    2T
    3H
    4H
    5Ti
    6H
    7H
    8H
    pattern
    0
    1
    2
    3H
    4H
    5T
    6H
    7H
    8H
    j
    3
    comparisons
    7

    5T matches T, so j becomes 3.

  6. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8Hi
    pattern
    0
    1
    2
    3H
    4H
    5T
    6H
    7H
    8H
    j
    6
    comparisons
    10

    6Text positions 6, 7 and 8 match, so j reaches 6, the length of the pattern.

  7. text
    0H
    1H
    2T
    3H
    4H
    5T
    6H
    7H
    8H
    pattern
    0
    1
    2
    3H
    4H
    5T
    6H
    7H
    8H
    found at
    3
    comparisons
    10
    naive
    15

    7The match starts at 8 − 6 + 1 = 3, found in 10 comparisons instead of 15. The index i never moved backwards.

1 / 7
KMP
function buildTable(pattern) {
  const table = new Array(pattern.length).fill(0);
  let k = 0; // length of the current border
  for (let i = 1; i < pattern.length; i++) {
    while (k > 0 && pattern[i] !== pattern[k]) k = table[k - 1];
    if (pattern[i] === pattern[k]) k++;
    table[i] = k;
  }
  return table;
}
 
function kmpSearch(text, pattern) {
  if (pattern.length === 0) return [];
  const table = buildTable(pattern);
  const found = [];
  let j = 0; // pattern characters matched so far
  for (let i = 0; i < text.length; i++) {
    while (j > 0 && text[i] !== pattern[j]) j = table[j - 1];
    if (text[i] === pattern[j]) j++;
    if (j === pattern.length) {
      found.push(i - j + 1);
      j = table[j - 1]; // keep going: matches can overlap
    }
  }
  return found;
}
def build_table(pattern):
    table = [0] * len(pattern)
    k = 0  # length of the current border
    for i in range(1, len(pattern)):
        while k > 0 and pattern[i] != pattern[k]:
            k = table[k - 1]
        if pattern[i] == pattern[k]:
            k += 1
        table[i] = k
    return table
 
def kmp_search(text, pattern):
    if not pattern:
        return []
    table = build_table(pattern)
    found = []
    j = 0  # pattern characters matched so far
    for i, ch in enumerate(text):
        while j > 0 and ch != pattern[j]:
            j = table[j - 1]
        if ch == pattern[j]:
            j += 1
        if j == len(pattern):
            found.append(i - j + 1)
            j = table[j - 1]  # keep going: matches can overlap
    return found

After a full match the code sets j = table[j − 1] instead of 0, so that overlapping matches are also reported. For example, AA occurs twice in AAA.

The inner while loop does not make the search O(n·m). The value of j rises by at most 1 per text character, and each fallback lowers it, so the total number of fallbacks cannot exceed the total number of increases, which is at most n. The search therefore does at most about 2n steps, and the table construction follows the same argument for m.

Rabin-Karp

Rabin-Karp compares numbers instead of strings. It converts every window of m characters in the text into a number called a hash and compares it with the pattern's hash. Comparing two numbers takes O(1), and the method works because each window's hash can be computed from the previous window's hash in O(1) instead of from scratch.

The idea is easiest to see with digits. To search for 265 in 31415926535, the first window is 314. To move one position right, remove the leading digit by subtracting 3 × 100, shift the rest left by multiplying by 10, and add the new digit: (314 − 300) × 10 + 1 = 141.

Rolling the window to find 265Use the arrows or ← → keys
target = value(p), h = value(text[0..m-1])for start from 0 to n - m:  if h == target and window == p: record start  h = (h - text[start] * 100) * 10 + text[start + m]
  1. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    314

    1The pattern's number is 265 and the first window of three digits is 314, so they are not equal.

  2. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    141

    2Rolling the window (a rolling hash) gives (314 − 300) × 10 + 1 = 141.

  3. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    415

    3The next window is (141 − 100) × 10 + 5 = 415, which is not equal to 265.

  4. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    159

    4Then (415 − 400) × 10 + 9 = 159.

  5. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    592

    5Then (159 − 100) × 10 + 2 = 592.

  6. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    926

    6Then (592 − 500) × 10 + 6 = 926.

  7. text
    03
    11
    24
    31
    45
    59
    62
    76
    85
    93
    105
    target
    265
    h
    265
    found at
    6

    7Finally (926 − 900) × 10 + 5 = 265. The numbers match and the digits agree, so the pattern is found at index 6 after looking at 7 windows.

1 / 7

For real text, treat each character code as a digit in base 256, and keep every value modulo a large prime such as 1,000,000,007 so the numbers stay small. The modulo creates a cost, because different windows can now have the same hash. With modulo 7, for example, both 314 and 265 leave remainder 6. An equal hash therefore only means that the window might match, and the code must compare the actual characters before reporting it. A different hash proves the window does not match, and that is what lets most windows be skipped.

Rabin-Karp
function rabinKarp(text, pattern) {
  const n = text.length, m = pattern.length;
  const BASE = 256, MOD = 1_000_000_007;
  if (m === 0 || m > n) return [];
  let high = 1; // BASE^(m-1) % MOD: the weight of the leading character
  for (let i = 0; i < m - 1; i++) high = (high * BASE) % MOD;
  let target = 0, h = 0;
  for (let i = 0; i < m; i++) {
    target = (target * BASE + pattern.charCodeAt(i)) % MOD;
    h = (h * BASE + text.charCodeAt(i)) % MOD;
  }
  const found = [];
  for (let start = 0; start + m <= n; start++) {
    if (h === target && text.slice(start, start + m) === pattern) found.push(start);
    if (start + m < n) {
      h = (h - (text.charCodeAt(start) * high) % MOD + MOD) % MOD; // drop the left char
      h = (h * BASE + text.charCodeAt(start + m)) % MOD;           // add the right char
    }
  }
  return found;
}
def rabin_karp(text, pattern):
    n, m = len(text), len(pattern)
    BASE, MOD = 256, 1_000_000_007
    if m == 0 or m > n:
        return []
    high = pow(BASE, m - 1, MOD)  # the weight of the leading character
    target = h = 0
    for i in range(m):
        target = (target * BASE + ord(pattern[i])) % MOD
        h = (h * BASE + ord(text[i])) % MOD
    found = []
    for start in range(n - m + 1):
        if h == target and text[start:start + m] == pattern:
            found.append(start)
        if start + m < n:
            h = (h - ord(text[start]) * high) % MOD   # drop the left char
            h = (h * BASE + ord(text[start + m])) % MOD  # add the right char
    return found
ApproachTimeSpaceWhy
NaiveO(n·m)O(1)Up to m comparisons at each of about n starts.
KMPO(n + m)O(m)The table takes O(m) to build, and the text pointer never moves back.
Rabin-KarpO(n + m) expectedO(1)Each roll costs O(1), plus m for each hash match. It degrades to O(n·m) if most windows match or collide.

Choosing between the methods

For everyday work, call the language's own search function, such as indexOf in JavaScript or str.find in Python. It is already optimised and tested. Write KMP or Rabin-Karp yourself when an interviewer asks for it.

When to use KMP

Use KMP when you need a worst-case guarantee for a single pattern, or when the failure table is the point of the problem.

When to use Rabin-Karp

Rabin-Karp is the better fit when you must compare many windows at once. To find a repeated substring of a given length, put the hash of every window in a hash set and look for a hash that appears twice, then verify the candidates. Its weakness is that the O(n + m) bound is only expected: a poor hash or an adversarial input that causes many collisions pushes it back toward O(n·m).

All three methods match an exact string. If the pattern is a regular expression, or if small differences must be allowed, as in spell checking, you need a regex engine or an edit-distance approach such as dynamic programming on strings. If you must search for a large set of different words in one text, running KMP once per word is slow, and a trie-based method such as Aho-Corasick is the standard answer.

Two other exact-matching algorithms come up in interviews. The Z-function gives, for every position, the length of the longest substring starting there that is also a prefix of the string, and it solves the same problems as the failure table. Boyer-Moore compares the pattern from its right end and skips several text characters after a mismatch, which makes it the fastest in practice for long patterns.

What interviewers ask about string matching

The usual form of the question is about finding one string inside another, usually phrased as "return the index of the first occurrence" or "does this string contain that one". Related forms are a prefix that is also a suffix, a string built by repeating a shorter one, or a repeated substring. If the constraints allow O(n·m), for example when both strings are under a few thousand characters, the naive scan is acceptable, and you should say so before you offer anything more complex.

Questions to expect:

  • "What is the naive approach and when does it get slow?" It tries every start position and compares up to m characters at each, so it takes O(n·m).
  • "What does the failure table store?" For each prefix of the pattern, it stores the length of the longest proper prefix that is also a suffix of that prefix. On a mismatch after j matched characters, that length tells KMP how many of those characters are still a valid match, so the search resumes at table[j − 1] without moving back in the text.
  • "Why is KMP O(n + m) when it has a loop inside a loop?" The pattern index j increases by at most one per text character, and every fallback decreases it. The total number of fallbacks is therefore at most the total number of increases, which is at most n. The table build follows the same reasoning.
  • "What is the worst case for Rabin-Karp?" It is O(n·m). If many windows have the same hash as the pattern, the algorithm compares characters for each of them. With a good modulus and base that is unlikely on ordinary input, which is why the expected time is O(n + m).
  • "How would you check whether a string is made of a shorter string repeated?" Build the failure table and let L = n − table[n − 1]. If table[n − 1] is greater than 0 and L divides n, the first L characters repeat to form the string.
  • "Why not just use indexOf?" In production you should. The interviewer is asking whether you understand what it does, so be ready to explain the failure table and the O(n + m) guarantee, and to say that the built-in version may use a different algorithm.
  • "How do you make Rabin-Karp reliable?" Use a large prime modulus and always compare the characters when the hashes are equal. To make collisions harder for an adversary to construct, pick the base at random or use two different moduli.
Quick check

What is the failure table for the pattern ABAB?

KMP has a while loop inside a for loop over the text. Why is the search still O(n)?

In Rabin-Karp, a window's hash equals the pattern's hash. What does that tell you?