KMP Failure Function Pattern Match Typed

Match a pattern in text using typed KMP with a precomputed failure function for linear time matching.

TypescriptData Fetching

Code

snippet
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;
}