The problem
Given a text of length n and a non-empty pattern of length m, report every index s where
text[s .. s + m) equals the pattern. Occurrences may overlap: "abab" occurs at 0, 2 and 7 in
"abababcabab". All four listings return the full list; an empty pattern is rejected, because "every
position matches" is a convention, not an answer.
Naive search
Lay the pattern on the text at every alignment s = 0 … n − m and compare left to right until a mismatch or the end of the pattern.
for s in 0 .. n - m:
j = 0
while j < m and text[s + j] == pattern[j]:
j = j + 1
if j == m: report s
On ordinary text most alignments fail on the first or second character, so it is fast in practice. Its worst case is (n − m + 1) · m comparisons: a run of a's with the pattern "aaaab". Every alignment matches four characters and then fails. The lab's Naive: worst case preset needs 16 alignments × 5 comparisons = 80. The waste is clear in the trace: after matching "aaaa" at s, the search moves to s + 1 and compares the same text characters again, although it already knows what they are.
Borders and the prefix function
A border of a string is a proper prefix that is also a suffix. "abab" has the border "ab"; "aaaa" has "aaa", "aa" and "a"; "abc" has none (the empty border, length 0).
The prefix function stores, for every prefix of the pattern, the length of its longest border:
lps[q] = length of the longest proper prefix of pattern[0..q] that is also a suffix of it
| q | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| pattern[q] | a | a | b | a | a | a | b |
| lps[q] | 0 | 1 | 0 | 1 | 2 | 2 | 3 |
Why it matters: suppose j characters of the pattern matched and the next one fails. The text just
read ends with pattern[0..j). The next alignment that could still succeed is the one where a
prefix of the pattern lines up with a suffix of what was matched, and the longest such overlap is
exactly the border of pattern[0..j), of length lps[j − 1]. Shorter overlaps are tried later by
falling back again.
Building the table
The table is built by matching the pattern against itself, with the same fallback idea:
lps[0] = 0; k = 0 # k = length of the current border
for q in 1 .. m - 1:
while k > 0 and pattern[q] != pattern[k]:
k = lps[k - 1] # try the next shorter border
if pattern[q] == pattern[k]:
k = k + 1 # the border grows by one character
lps[q] = k
In the KMP: rich table preset, at q = 5 the border "aa" (k = 2) cannot be extended because
pattern[5] = 'a' differs from pattern[2] = 'b'. k falls back to lps[1] = 1, pattern[5] equals
pattern[1], and lps[5] = 2. The lab draws the prefix being extended in a row behind the pattern,
shifted so that the two characters being compared line up.
The KMP scan
j = 0 # pattern characters matched
for i in 0 .. n - 1:
while j > 0 and text[i] != pattern[j]:
j = lps[j - 1] # slide the pattern; i stays
if text[i] == pattern[j]:
j = j + 1
if j == m:
report i - m + 1
j = lps[m - 1] # keep the overlap: occurrences may overlap
Invariant: before comparing text[i], the j characters text[i − j .. i) equal pattern[0 .. j).
A fallback replaces j with a smaller border length, which keeps the invariant because a border is
both a prefix and a suffix. The unit tests check this invariant at every step of 200 random runs.
After a match, j = lps[m − 1] lets the next occurrence reuse the overlap. That is how KMP:
overlapping finds "abab" at 0 and 2 without rereading.
Why KMP is O(n + m)
Count how j changes during the scan. Each iteration of the for loop increases j by at most 1, so j grows by at most n in total. Each fallback decreases j by at least 1, and j never goes below 0. So there are at most n fallbacks over the whole scan: at most 2n comparisons. The same argument on k bounds the table construction by 2m. Total O(n + m) time and O(m) extra space for the table.
On the naive worst-case input, KMP needs 42 comparisons (7 for the table, 35 for the scan) instead of 80, and the gap grows with m: for a pattern of a hundred a's followed by a b, the naive search does about 100 comparisons per alignment, KMP about 2 per text character.
| Preprocessing | Search | Extra space | Text index moves back? | |
|---|---|---|---|---|
| Naive | none | O(n · m) worst, often near O(n) | O(1) | yes |
| KMP | O(m) | O(n) | O(m) | never (good for streams) |
Because i only moves forward, KMP can search a stream it reads once, such as a network socket, without buffering the text.
What the built-ins do
| Language | Call | Compares | Notes |
|---|---|---|---|
| C# | text.IndexOf(pattern, StringComparison.Ordinal) |
UTF-16 units | Without Ordinal, the string overload uses culture-aware rules (CurrentCulture), which is slower and can match differently. Vectorised search internally. |
| Java | text.indexOf(pattern, from) |
UTF-16 units | No culture rules. Loop with from = found + 1 to get overlapping occurrences. |
| Python | text.find(pattern, start) |
code points | CPython uses a tuned two-way / Boyer–Moore–Horspool hybrid. re.finditer does not report overlapping matches unless you use a lookahead. |
| C++ | text.find(pattern, pos); std::search with std::boyer_moore_searcher (C++17) |
bytes (char) |
find returns std::string::npos when there is no match. |
Use the built-in in production; it is tested, vectorised and often sub-linear on average. Write KMP
when you need its guarantees (worst-case linear, streaming, no backtracking) or its prefix table for
other problems: the shortest period of a string is m − lps[m − 1], and searching for p in
p + '#' + text turns the table itself into a matcher.
Language notes
The listings compare code units (C#, Java), code points (Python) and bytes (C++), and each test suite pins that down:
- C# / Java: in "a😀b😀" the pattern "b😀" is found at index 3, because the emoji before it takes
two UTF-16 units. Indices from
IndexOfandindexOfcount units too. - Python: the same search returns 2:
strindexes code points. - C++:
std::string_viewholds bytes. Searching UTF-8 for a UTF-8 pattern is still correct, because UTF-8 is self-synchronising (a continuation byte can never match a lead byte), but the indices are byte offsets. The C++ naive loop is writtens + m <= nrather thans <= n − m: with unsignedstd::size_t,n − mwraps around to a huge number when m > n. - Normalisation: "café" with precomposed é and "cafe" + U+0301 do not match ordinally in any language. Normalise both strings first if they come from different sources.
Common mistakes
- Resetting j to 0 after a mismatch instead of falling back with
lps[j − 1]: that is the naive search with extra steps, and it misses overlapping occurrences. - Using
lps[j]instead oflps[j − 1]. The border you need belongs to the matched partpattern[0..j), whose last index is j − 1. - Including the whole string as its own border. lps uses proper prefixes; otherwise lps[q] would always be q + 1 and the fallback would loop forever.
- Moving i back. KMP never does; if your version does, the analysis no longer applies.
- Forgetting
j = lps[m − 1]after a match, which either reads past the pattern or loses overlapping matches.
Edge cases
- Pattern longer than the text: no alignment fits; the naive loop body never runs, KMP scans and finds nothing.
- Empty text: no matches.
- Pattern of length 1: lps = [0]; KMP and naive do the same n comparisons.
- Periodic patterns ("abcabc") have large lps values and produce overlapping matches.
Worked practice
1. Compute lps for "abcabd".
Answer
[0, 0, 0, 1, 2, 0]. "abca" has border "a", "abcab" has "ab", and "abcabd" has none because "d" cannot extend "ab" (pattern[2] = 'c') or the empty border (pattern[0] = 'a').
2. During a scan with pattern "abcabd", j = 5 ("abcab" matched) and the next text character is 'c'. What happens?
Answer
'c' differs from pattern[5] = 'd', so j = lps[4] = 2: "ab" stays matched. Then 'c' equals pattern[2], so j = 3. The text index did not move back.
3. What is the shortest period of "abababab"?
Answer
lps[7] = 6, so the period is 8 − 6 = 2: the string is "ab" repeated.
4. Give an input where the naive search does about n · m comparisons.
Answer
Text "aaaa…a" (n a's), pattern "aa…ab" (m − 1 a's then b). Every alignment matches m − 1 characters before failing on the b.
Summary
- Naive search: simple, often fast, but O(n · m) in the worst case because it forgets what it matched.
- lps[q] is the longest proper border of
pattern[0..q]; it is built in O(m) by matching the pattern against itself. - KMP falls back to
lps[j − 1]after a mismatch and never moves backwards in the text: O(n + m). - Built-ins are faster in practice; know whether they compare units, code points or bytes, and whether they are culture-aware.