Categories
interview

KMP (Knuth–Morris–Pratt) Algorithm

// Knuth–Morris–Pratt algorithm.
const patternMatch = function(pattern, str) {
  let i = 0;
  let j = 0;
  let n = str.length;
  let m = pattern.length;
  const lps = [];

  // Compute longest prefix string.
  computeLPS(pattern, m, lps);

  while (i < n) {
    if (str.charAt(i) === pattern.charAt(j)) {
      i++;
      j++;
    }
    if (j === m) {
      console.log('String found at: ' + (i - j));
      j = lps[j - 1];
    } else if (i < n && str.charAt(i) !== pattern.charAt(j)) {
      if (j !== 0) {
        j = lps[j - 1];
      } else {
        i++;
      }
    }
  }
};

const computeLPS = function(pattern, m, lps) {
  let i = 1;
  let len = 0;
  while (i < m) {
    if (pattern.charAt(i) === pattern.charAt(len)) {
      lps[i++] = ++len;
    } else {
      if (len > 0) {
        len = lps[len - 1];
      } else {
        lps[i++] = 0;
      }
    }
  }
};

patternMatch('john', 'helloworldjohnhelloworldjohnn');
/*
"String found at: 10"
"String found at: 24"
*/

Demo