Comparing substring search algorithms
Find ABABAC in XXABABABAC four ways. Every method finds the same match. One tests the next start from scratch, one keeps symbols that already matched, one skips starts, and one checks hashes first.
Video walkthrough
How to read the interactive
The top row is the shared text. Below it are four alignments of the same pattern. During the search, a highlighted pattern symbol is compared with the text symbol above it. Green bands mark confirmed matches. Positions start at 1.
KMP fills its prefix table first. Then each unfinished search performs its next operation on each step. That may be a symbol comparison, a hash check, or a window shift. Use steps to follow each search and the separate counters to compare the work.
Four ways to reach position 5
Naive search tries every possible start and compares left to right. At position 3, five symbols match before the B in the text differs from the C in the pattern. The search starts over at position 4 and finds the match at position 5.
KMP has already built its prefix table. In the matched fragment ABABA, the beginning ABA is also its end. KMP keeps those three symbols, shifts the pattern, and checks the same B again. This time it lines up with a B in the pattern.
Horspool compares right to left. At positions 1 and 3, the window ends in B and the pattern ends in C. The shift table says to move two places after seeing B, so the search skips positions 2 and 4. At position 5 it compares all the way to the left edge and confirms the match.
Rabin–Karp hashes the pattern and the first window. Each shift removes the outgoing symbol’s contribution and adds the incoming one according to its place value. The hashes differ until position 5. There they agree, so the algorithm checks all six symbols.
What the counters measure
A symbol comparison checks one pair from the text and pattern. KMP's comparisons within the pattern during preparation have their own counter. Horspool shows skipped starts. Rabin–Karp counts hash checks and false hash matches separately. Building Horspool's shift table and computing rolling hashes do not count as symbol comparisons.
On this short text, KMP reduces comparisons in the text from 15 to 11. It spends another seven on the table, for a total of 18. The table can be reused when searching for the same pattern again.
Try the “Hash collision” example. BD and AA give the same hash, but comparing B with A rules out BD. The demo uses a small modulus of 13 to make this visible. The “Overlapping matches” example shows how the algorithms keep searching after a match and report positions 1, 3, and 5.
| Algorithm | Symbol comparisons in the text | Other counts |
|---|---|---|
| Naive search | 15 | — |
| KMP | 11 | 7 preparation comparisons |
| Horspool | 8 | 2 skipped starts |
| Rabin–Karp | 6 | 5 hash checks, 0 collisions |
What changes on longer strings
Let n be the text length and m the pattern length. Naive search and Horspool take O(nm) time in the worst case. Horspool can skip many starts when the symbol at the end of the window gives a large shift. KMP builds the table in O(m) and scans the text in O(n).
Rabin–Karp computes the initial hashes in O(m) and shifts the window in O(1). If the hashes agree often, symbol checks can bring the worst case to O(nm). The counters show how often those checks were needed on a particular input.
Given arrays of symbols, naive search and Rabin–Karp use O(1) working space. KMP stores O(m) prefix lengths, and Horspool stores up to O(m) entries for distinct pattern symbols. The code below uses another O(n + m) space for its input arrays. Results are stored separately. The interactive also stores its step history.
JavaScript implementations
The code finds every occurrence, preserves spaces, and distinguishes case. A symbol is one Unicode code point, just as in the interactive.
Naive search and KMP
function compareSubstringSearch(text, pattern) {
const source = Array.from(text);
const needle = Array.from(pattern);
const ordinary = { positions: [], comparisons: 0 };
const kmp = { positions: [], comparisons: 0, preparation: 0 };
if (needle.length === 0) throw new RangeError("Empty pattern");
if (needle.length > source.length) return { ordinary, kmp };
for (let start = 0; start + needle.length <= source.length; start++) {
for (let j = 0; j < needle.length; j++) {
ordinary.comparisons++;
if (source[start + j] !== needle[j]) break;
if (j === needle.length - 1) ordinary.positions.push(start + 1);
}
}
const prefix = [0];
for (let i = 1, size = 0; i < needle.length;) {
kmp.preparation++;
if (needle[i] === needle[size]) prefix[i++] = ++size;
else if (size > 0) size = prefix[size - 1];
else prefix[i++] = 0;
}
for (let i = 0, j = 0; i < source.length;) {
kmp.comparisons++;
if (source[i] === needle[j]) {
i++;
j++;
if (j === needle.length) {
kmp.positions.push(i - j + 1);
j = prefix[j - 1];
}
} else if (j > 0) {
j = prefix[j - 1];
} else {
i++;
}
}
return { ordinary, kmp };
}Horspool
function horspoolSearch(text, pattern) {
const source = Array.from(text);
const target = Array.from(pattern);
const size = target.length;
if (!size) throw new RangeError("The pattern must not be empty");
const shifts = new Map();
for (let j = 0; j < size - 1; j++) {
shifts.set(target[j], size - 1 - j);
}
const positions = [];
let comparisons = 0;
for (let start = 0; start + size <= source.length;) {
let j = size - 1;
while (j >= 0) {
comparisons++;
if (source[start + j] !== target[j]) break;
j--;
}
if (j < 0) positions.push(start + 1);
const rightEdge = source[start + size - 1];
start += shifts.get(rightEdge) ?? size;
}
return { positions, comparisons };
}Rabin–Karp
function rabinKarpSearch(text, pattern) {
const source = Array.from(text);
const target = Array.from(pattern);
const m = target.length;
if (m === 0) throw new RangeError("The pattern must not be empty");
const base = 10;
const modulus = 13;
const mod = value => ((value % modulus) + modulus) % modulus;
const code = symbol => {
const point = symbol.codePointAt(0);
return point >= 65 && point <= 90 ? point - 64 : point + 27;
};
const hash = symbols => {
let value = 0;
for (let j = 0; j < m; j++) value = mod(value * base + code(symbols[j]));
return value;
};
const result = { positions: [], hashChecks: 0, symbolChecks: 0, collisions: 0 };
if (m > source.length) return result;
let weight = 1;
for (let j = 1; j < m; j++) weight = mod(weight * base);
const patternHash = hash(target);
let windowHash = hash(source);
const last = source.length - m;
for (let start = 0; start <= last; start++) {
result.hashChecks++;
if (windowHash === patternHash) {
let j = 0;
while (j < m) {
result.symbolChecks++;
if (source[start + j] !== target[j]) break;
j++;
}
if (j === m) result.positions.push(start + 1);
else result.collisions++;
}
if (start < last) {
const remaining = mod(windowHash - code(source[start]) * weight);
windowHash = mod(remaining * base + code(source[start + m]));
}
}
return result;
}