GeeksforGeeks Hard

Search Pattern (KMP Algorithm)

Search Pattern (KMP Algorithm) is a GFG problem (Hard). Given a text txt and a pattern pat, both lowercase, return the 0-based start index of every occurrence of pat in txt, or an empty list if there is none.

  • Occurrences may overlap, and each one must be reported.
  • Both strings can be 10⁵ letters long. Checking every start against the whole pattern is O(n·m), which is too slow on inputs like "aaa…ab", so the expected time is O(n + m) with O(m) extra space.
Constraints
  • 1 <= pat.length <= txt.length <= 10⁵
  • Both strings use lowercase English letters
stringkmppattern-matching
Open on GeeksforGeeks ↗
02

Intuition

When a match breaks after j letters, those j text letters are already known: they equal pat[0..j−1]. So where the next copy could start depends only on the pattern, and can be worked out before the text is read.

  • The LPS array (longest prefix suffix): lps[i] is the longest proper prefix of pat[0..i] that is also its suffix, called a border.
  • The fallback: on a mismatch after j matched letters, keep lps[j − 1] of them matched and try the same text letter again.

The text pointer never moves back, which is what makes KMP pattern search linear.

How to spot this pattern

Exact search for one fixed pattern, with a demand for linear time and nothing allowed to re-read the text, points to KMP. The same table also answers "longest prefix that is also a suffix" and "is this string a repeat of a shorter block?".

03

Approach

Try it first

Before reading on, search for "abab" in "abaababab" by hand. When the fourth letter fails at text spot 3, which of the three letters you just matched could still be the start of a copy?

1

Build the LPS array on the pattern

Set lps[0] = 0 and keep k, the length of the current border. For each i from 1, compare pat[i] with pat[k]. A match means the border grows to k + 1, because the old border plus one equal letter is still a prefix and a suffix.

2

Fall back through shorter borders

While k > 0 and pat[i] != pat[k], set k = lps[k - 1]. Any shorter border of pat[0..i-1] is also a border of the current border, so the table already lists the next candidate, from longest to shortest.

3

Scan the text once

Keep j, the number of pattern letters matched so far. For each text letter, fall back with j = lps[j - 1] while it differs from pat[j], then add 1 to j if it matches. The text index only ever moves forward.

4

Record a match and keep going

When j == m, the pattern ends at text index i, so append i - m + 1. Then set j = lps[m - 1] rather than 0, because the end of this copy may already be the start of the next one.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def search(self, pat: str, txt: str) -> list[int]:
▶3 m = len(pat)
▶4 lps = [0] * m
▶5 k = 0
▶6 for i in range(1, m):
▶7 while k > 0 and pat[i] != pat[k]:
▶8 k = lps[k - 1]
▶9 if pat[i] == pat[k]:
▶10 k += 1
▶11 lps[i] = k
▶12 res = []
▶13 j = 0
▶14 for i, c in enumerate(txt):
▶15 while j > 0 and c != pat[j]:
▶16 j = lps[j - 1]
▶17 if c == pat[j]:
▶18 j += 1
▶19 if j == m:
▶20 res.append(i - m + 1)
▶21 j = lps[j - 1]
▶22 return res
patterna0b1a2b3pattern copy lined upborder tablea0babborder lengthfound atfirst letter: border 0
border0
Before reading the text, build a table on the pattern alone. Entry i is the length of the longest proper prefix of the first i + 1 letters that is also their suffix, called the border. A single letter has no proper prefix, so its border is 0.
patterna0b1a2b3pattern copy lined upababorder tablea0b0abborder lengthfound atb differs from a, nothing left → border 0
i1
border0
Even the empty border cannot grow: letter 1 (b) differs from the first letter. So no prefix of the first 2 letters is also their suffix, and the entry is 0.
patterna0b1a2b3pattern copy lined upabborder tablea0b0a1bborder lengthfound ata matches a → border 1
i2
border1
Letter 2 matches letter 0, so the border grows by one: the first 3 letters start and end with the same 1.
patterna0b1a2b3pattern copy lined upabborder tablea0b0a1b2border lengthfound atb matches b → border 2
i3
border2
Letter 3 matches letter 1, so the border grows by one: the first 4 letters start and end with the same 2.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata matches a → 1 matched
text spot0
matched1
Text letter 0 equals pattern letter 0, so 1 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound atb matches b → 2 matched
text spot1
matched2
Text letter 1 equals pattern letter 1, so 2 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata matches a → 3 matched
text spot2
matched3
Text letter 2 equals pattern letter 2, so 3 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata differs from b → keep 1 matched
text spot3
matched3
keep1
The text letter a breaks a run of 3 matched letters. Those 3 letters are the pattern's own start, and entry 2 of the table says their longest border is 1. So the pattern slides right and 1 letters still line up, with no step back in the text.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata differs from b → keep 0 matched
text spot3
matched1
keep0
The text letter a breaks a run of 1 matched letters. Those 1 letters are the pattern's own start, and entry 0 of the table says their longest border is 0. So the pattern slides right and 0 letters still line up, with no step back in the text.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata matches a → 1 matched
text spot3
matched1
Text letter 3 equals pattern letter 0, so 1 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound atb matches b → 2 matched
text spot4
matched2
Text letter 4 equals pattern letter 1, so 2 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound ata matches a → 3 matched
text spot5
matched3
Text letter 5 equals pattern letter 2, so 3 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound atb matches b → 4 matched
text spot6
matched4
Text letter 6 equals pattern letter 3, so 4 of 4 letters now match. That is the whole pattern.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound at3all 4 match → found at 3, keep 2
found3
keep2
The pattern ends at text spot 6, so it starts at 3. To catch overlapping copies, do not reset to 0: the last table entry says the final 2 letters are also the pattern's start, so the scan carries on with 2 matched.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound at3a matches a → 3 matched
text spot7
matched3
Text letter 7 equals pattern letter 2, so 3 of 4 letters now match.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound at3b matches b → 4 matched
text spot8
matched4
Text letter 8 equals pattern letter 3, so 4 of 4 letters now match. That is the whole pattern.
texta0b1a2a3b4a5b6a7b8pattern lined upababborder tablea0b0a1b2border lengthfound at35all 4 match → found at 5, keep 2
found5
keep2
The pattern ends at text spot 8, so it starts at 5. To catch overlapping copies, do not reset to 0: the last table entry says the final 2 letters are also the pattern's start, so the scan carries on with 2 matched.
texta0b1a2a3b4a5b6a7b8pattern lined upborder tablea0b0a1b2border lengthfound at35done: found at 3 and 5
answer3, 5
The text was read once, left to right, and the text position never moved back. Every start index was recorded as its match finished.
05

Common pitfalls

Resetting to 0 after a full match

✗ Wrong
if j == m:
    res.append(i - m + 1)
    j = 0
✓ Right
if j == m:
    res.append(i - m + 1)
    j = lps[j - 1]

Overlapping copies are lost. For pat = "aa" and txt = "aaa" the reset version returns [0], because the second a is forgotten. Keeping the border of 1 gives [0, 1].

Falling back only once

✗ Wrong
if j > 0 and c != pat[j]:
    j = lps[j - 1]
✓ Right
while j > 0 and c != pat[j]:
    j = lps[j - 1]

One fallback can still leave a mismatch. For pat = "aaa" and txt = "aabaa", the b drops j from 2 to 1 and stops there, so the run wrongly survives the b and a false match at 2 is reported. The correct answer is empty.

06

Edge cases

A single-letter pattern

The table is just [0], so after each hit j falls back to 0 and every position holding that letter is reported.

A pattern with no repeated start, such as "abcd"

Every entry is 0, so each mismatch restarts the pattern at the current text letter. It still never re-reads earlier text.

07

Complexity

Time
O(n + m)
Space
O(m)
Every match raises j by 1 and every fallback lowers it by at least 1. Since j never goes below 0, the fallbacks in the scan add up to at most n, and the same argument bounds the table build by m.
08

KMP against the Z function and brute force

Which tool to reach for when one fixed pattern has to be found in a text.

ApproachWork done up frontWorst-case timeMemoryPick it when
KMP (this page)LPS table on patO(n + m)O(m)the text is huge or can be read only once, left to right
Z functionZ values on the joined stringO(n + m)O(n + m)a shorter loop matters more than memory
Character-by-character scannoneO(n·m)O(1)only the first index is needed and inputs are small
09

Search Pattern (KMP Algorithm) FAQ

Why does the LPS array use proper prefixes only?

The whole string is always both a prefix and a suffix of itself, so allowing it would make every entry i + 1. Falling back to that length would never shorten the match, and the search would loop forever on the first mismatch.

Is KMP faster than a language's built-in find in practice?

Often not for ordinary text. Built-in search uses tuned loops and heuristics that are fast on average. KMP's value is the worst-case guarantee: inputs like "aaaa…ab" that make a naive scan quadratic stay linear.

What if there are many patterns to search for at once?

Running KMP once per pattern costs a full text pass each time. Aho-Corasick generalises the LPS fallback to a trie of all patterns, so one pass over the text finds every pattern.