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;
}Report a problem with this exampleOpens a pre-filled issue on GitHub.