Skip to content
Menu
Portfolio
  • Artificial Intelligence
  • Personal Projects
  • Assignments
  • Algorithms
  • Notes
  • Home
Portfolio

KMP Algorithm

Posted on August 5, 2023May 18, 2026

KMP (Knuth–Morris–Pratt) is a classic string matching algorithm used to efficiently determine whether a pattern string appears in a long text.

The core idea of KMP is:

When a mismatch occurs, instead of moving the text pointer backward, KMP uses previously matched information to quickly shift the pattern.

j = ne [ j ] ➡️ If the longest matching prefix fails, fall back to the second-longest matching prefix.

Python Template for KMP Algorithm:

# The template is based on 1-indexed array

ne = [0] * (n + 1)

# Build the prefix table {next array}
j = 0
for i in range(2, n + 1):
    while j and p[i] != p[j + 1]:
        j = ne[j]
    if p[i] == p[j + 1]:
        j += 1
    ne[i] = j

# KMP matching
j = 0
for i in range(1, m + 1):
    while j and s[i] != p[j + 1]:
        j = ne[j]
    if s[i] == p[j + 1]:
        j += 1
    if j == n:
        # find matching

Key Points:

  1. Pad to make Pattern and Source all 1-indexed
  2. Createt the next(prefix) table

CATEGORIES

  • Artificial Intelligence
  • Personal Projects
  • Notes
  • Algorithms

  • University of Maryland
  • CMSC426 - Computer Vision
  • CMSC320 - Introduction to Data Science
  • CMSC330 - Organization of Programming Languages
  • CMSC216 - Introduction to Computer Systems
©2026 Portfolio | WordPress Theme by Superbthemes.com