KMP Failure Function Pattern Match (JavaScript)
Match a pattern in text using the Knuth Morris Pratt algorithm with a precomputed failure function for linear time matching.
Code
function kmpSearch(text, pattern) {
const n = text.length, m = pattern.length;
if (m === 0) return [0];
const fail = new Array(m).fill(0);
for (let i = 1, j = 0; i < m; i++) {
while (j > 0 && pattern[i] !== pattern[j]) j = fail[j - 1];
if (pattern[i] === pattern[j]) j++;
fail[i] = j;
}
const result = [];
for (let i = 0, j = 0; i < n; i++) {
while (j > 0 && text[i] !== pattern[j]) j = fail[j - 1];
if (text[i] === pattern[j]) j++;
if (j === m) { result.push(i - m + 1); j = fail[j - 1]; }
}
return result;
}How it works
Count the function kmpSearch as the entire surface area of KMP Failure Function Pattern Match (JavaScript).
The core work runs in nested loops — outer for (let i = 1, j = 0; i < m; i++), inner while (j > 0 && pattern[i] !== pattern[j]) j = fail[j - 1];.
The return value is newly constructed — inputs are never handed back.
What to watch for
- The guard
m === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is function kmpSearch(text, pattern)
Statements that matter
if (m === 0) return [0];
Interactive Tools for This Topic
FAQ
- Does `kmpSearch` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `kmpSearch` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.