Builds onArrays and stringsHash map lookup
01The idea
The basic string search tries every starting position in the text and compares the pattern there, character by character. With a text of length n and a pattern of length m, that can take O(n × m). On a text like "aaaa...ab" with the pattern "aaab", most starts match for a while and then fails, and all that work is wasted.
The Knuth-Morris-Pratt algorithm, KMP, never throws that work away. It first builds a table called lps, for "longest prefix that is also a suffix". lps[i] is the length of the longest proper prefix of the pattern that also ends at position i. "Proper" means shorter than the whole piece.
When a match fails after k matched characters, the last k characters of the text equal the first k of the pattern. Of those, the first lps[k - 1] also equal the last lps[k - 1]. So you can keep that much of the match and continue, instead of starting over. The text pointer never moves back, and the whole search is O(n + m).
The table is built the same way, by matching the pattern against itself. You can also use it for questions about one string, such as its shortest repeating unit or its longest prefix that is also a suffix.
A second approach is the rolling hash, also called Rabin-Karp. It turns each window of the text into a number and updates that number in O(1) as the window slides. Equal hashes point to a possible match, which you then confirm.
02How to spot it
Reach for these tools when:
- you must find a pattern in a long text, and the simple search could take O(n × m)
- the question is about prefixes that are also suffixes, or about a string made of a repeated piece
- you compare many substrings of the same length, where a rolling hash helps
- the limits are large, such as a text of 10⁵ characters and a pattern of 10⁴
For small inputs, Python's s.find(p) or Java's indexOf is fine and expected. Interviews ask for KMP or hashing when the point is the linear-time idea.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue