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.
On this page
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.
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- text0H1H2T3H4H5T6H7H8Hpattern0Hstart1H2T3H4H5H678
- comparisons
- 6
1At start 0, five characters match and then the text character
Tmeets the pattern characterH. That is 6 comparisons so far. - text0H1H2T3H4H5T6H7H8Hpattern01Hstart2H3T4H5H6H78
- comparisons
- 8
2The pattern slides to start 1 and the comparison begins again. Text positions 1 and 2 are read a second time, and
TagainstHfails. - text0H1H2T3H4H5T6H7H8Hpattern012Hstart3H4T5H6H7H8
- comparisons
- 9
3At start 2,
TagainstHfails on the first comparison. - text0H1H2T3H4H5T6H7H8Hpattern0123Hstart4H5T6H7H8H
- 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.
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.
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.
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.
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- pattern0Hk1H2T3H4H5Htable0012345
- k
- 0
1A single character has no border, so
table[0] = 0andk = 0. - pattern0Hk1Hi2T3H4H5Htable00112345
- k
- 1
2
p[1]andp[0]are both H, so the border grows to length 1. - pattern0H1Hk2Ti3H4H5Htable00112345
- k
- 0
3
p[2]is T butp[1]is H, so the border cannot grow andkfalls back totable[0] = 0. - pattern0Hk1H2Ti3H4H5Htable001120345
- k
- 0
4T does not match
p[0], which is H, sotable[2] = 0. - pattern0Hk1H2T3Hi4H5Htable0011203145
- k
- 1
5
p[3]matchesp[0], so the border length is 1. - pattern0H1Hk2T3H4Hi5Htable00112031425
- k
- 2
6
p[4]matchesp[1], so the border grows to length 2, which isHH. - pattern0H1H2Tk3H4H5Hitable00112031425
- k
- 1
7
p[5]is H butp[2]is T, sokfalls back to the border ofHH, which istable[1] = 1. - pattern0H1Hk2T3H4H5Hitable001120314252
- k
- 2
8H matches
p[1], sokbecomes 2 andtable[5] = 2. The finished table is[0, 1, 0, 1, 2, 2].
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.
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- text0Hi1H2T3H4H5T6H7H8Hpattern0H1H2T3H4H5H678
- j
- 0
- comparisons
- 0
1No characters have been matched yet.
- text0H1H2T3H4Hi5T6H7H8Hpattern0H1H2T3H4H5H678
- j
- 5
- comparisons
- 5
2Text positions 0 to 4 match the pattern, one comparison each, so
jis 5. - text0H1H2T3H4H5Ti6H7H8Hpattern0H1H2T3H4H5H678
- j
- 5
- comparisons
- 6
3At
i = 5the text character T meets the pattern character H, which is a mismatch. - text0H1H2T3H4H5Ti6H7H8Hpattern0123H4H5T6H7H8H
- j
- 2
- comparisons
- 6
4The search falls back to
j = table[4] = 2. The pattern is now effectively at start 3, andistays at 5. - text0H1H2T3H4H5Ti6H7H8Hpattern0123H4H5T6H7H8H
- j
- 3
- comparisons
- 7
5T matches T, so
jbecomes 3. - text0H1H2T3H4H5T6H7H8Hipattern0123H4H5T6H7H8H
- j
- 6
- comparisons
- 10
6Text positions 6, 7 and 8 match, so
jreaches 6, the length of the pattern. - text0H1H2T3H4H5T6H7H8Hpattern0123H4H5T6H7H8H
- found at
- 3
- comparisons
- 10
- naive
- 15
7The match starts at 8 − 6 + 1 = 3, found in 10 comparisons instead of 15. The index
inever moved backwards.
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 foundAfter 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.
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]- text03112431455962768593105
- target
- 265
- h
- 314
1The pattern's number is 265 and the first window of three digits is 314, so they are not equal.
- text03112431455962768593105
- target
- 265
- h
- 141
2Rolling the window (a rolling hash) gives (314 − 300) × 10 + 1 = 141.
- text03112431455962768593105
- target
- 265
- h
- 415
3The next window is (141 − 100) × 10 + 5 = 415, which is not equal to 265.
- text03112431455962768593105
- target
- 265
- h
- 159
4Then (415 − 400) × 10 + 9 = 159.
- text03112431455962768593105
- target
- 265
- h
- 592
5Then (159 − 100) × 10 + 2 = 592.
- text03112431455962768593105
- target
- 265
- h
- 926
6Then (592 − 500) × 10 + 6 = 926.
- text03112431455962768593105
- 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.
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.
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| Approach | Time | Space | Why |
|---|---|---|---|
| Naive | O(n·m) | O(1) | Up to m comparisons at each of about n starts. |
| KMP | O(n + m) | O(m) | The table takes O(m) to build, and the text pointer never moves back. |
| Rabin-Karp | O(n + m) expected | O(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
When to use the built-in search
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).
Other algorithms for related problems
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
mcharacters 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
jmatched characters, that length tells KMP how many of those characters are still a valid match, so the search resumes attable[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
jincreases 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 mostn. 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]. Iftable[n − 1]is greater than 0 andLdividesn, the firstLcharacters 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.
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?