Suppose a document has n characters and you want every occurrence of a pattern with m characters. A direct method tries the pattern at each possible starting position and compares characters until it matches or fails. It is easy to explain and can be fine for a short document. Its worst-case time is O((n − m + 1)m), because many starting positions may require many character checks.
Background for this page. A string is a sequence of characters. A prefix starts at the beginning; a suffix ends at the end. The text and pattern need consistent rules for case, characters, and indexing. Related explanations: Hash tables: collisions, load factor, and lookup · Big O, Big Omega, and Big Theta.
The input rule matters. Are uppercase and lowercase the same? Does a match count inside a larger word? Can matches overlap? Searching ana in banana finds two overlapping occurrences at positions 1 and 3. Searching aa in aaa also finds two, at positions 0 and 1. A program must decide whether to report both.
Rabin–Karp computes a hash of the pattern and of each text window of length m. A rolling hash updates the window hash as one character leaves and another enters. When hashes differ, the window cannot match. When hashes agree, the actual characters must still be checked because different strings can share a hash. With suitable assumptions it gives good expected behavior, while collisions can make the worst case slower.
Knuth–Morris–Pratt (KMP) avoids repeating comparisons after a mismatch. It first records how much of a pattern prefix is also a suffix of each prefix already examined. After a mismatch, it uses that information to move the pattern without discarding a possible match. Preprocessing and searching together take O(n + m) time, with O(m) extra space. A finite automaton offers another view: its state records how much of the pattern has matched, and each next character changes that state.
A suffix array stores the starting positions of all suffixes of a text in sorted order. Building it takes work and space, but it supports many later substring queries and other text operations. It is a different investment from running one search once. The best method depends on whether we search one pattern, many patterns, one document, or many documents.
Unicode adds a practical detail. A visible character may have more than one underlying representation, and case conversion varies across languages. A textbook method over a simple alphabet needs a defined text-normalization rule before it becomes a reliable search feature for real users.
Reuse a partial match instead of restarting
Suppose the pattern is ababac and five characters ababa have matched before a mismatch. The matched prefix ababa ends with aba, which is also a prefix of the pattern. KMP can retain that length-three candidate rather than treating every matched character as useless. Its prefix table records such fallback lengths.
This does not mean a mismatch always keeps three characters. The length depends on the pattern and the matched prefix, and more than one fallback may be needed before a character fits. Preprocessing costs O(m); searching costs O(n), because progress through the text and bounded fallback work can be charged across the scan.
Decide what an empty pattern means. Libraries may match it at every boundary, but an application may instead reject it. Unicode normalization can also make visually identical text have different underlying sequences.
Practice. Why must Rabin–Karp compare characters after two window hashes match? What does KMP remember so it can avoid moving the pattern back to the beginning after every mismatch?
Answer. A hash collision can make different strings share a hash, so the characters must confirm a match. KMP remembers the longest pattern prefix that could still be a suffix of what was just matched.
Try another case. Why can changing only the text’s case while leaving the pattern unchanged break a case-insensitive search?
Reasoning. The two sequences no longer use the same comparison rule. Apply the intended transformation consistently, and account for transformations that alter character positions.