KMP Failure Function Pattern Match Typed
Match a pattern in text using typed KMP with a precomputed failure function for linear time matching.
Code
function kmpSearch(text: string, pattern: string): number[] {
const n = text.length, m = pattern.length;
if (m === 0) return [0];
const fail: number[] = 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: number[] = [];
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 the snippet works
Count the function kmpSearch as the entire surface area of KMP Failure Function Pattern Match Typed.
The nesting pairs for (let i = 1, j = 0; i < m; i++) { while (j > 0 && pattern[i] !== pattern[j]) j = fail[j - 1]; … with for (let i = 0, j = 0; i < n; i++) { while (j > 0 && text[i] !== pattern[j]) j = fail[j - 1]; if … — the inner runs once per outer step.
The result is a fresh construction, so callers can keep their originals.
Caveats
- The guard
m === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The primary signature is function kmpSearch(text: string, pattern: string)
Key statements
if (m === 0) return [0];
Interactive Tools for This Topic
FAQ
- Does `kmpSearch` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `kmpSearch` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.