Practice Discrete Math

Algorithms / Prefix Function Kmp

Least You Need to Know: Prefix Function, Borders, and KMP Intuition

The **prefix function** tracks how much of a pattern already matches itself. That self-overlap information is what lets KMP avoid restarting from scratch after mismatches in pattern matching problems.

The least you need to know

Key notation

pi[i] length of the longest proper prefix of pattern[0..i] that is also a suffix
border string that is both a prefix and a suffix
fallback move to a shorter previously known border after mismatch

Tiny worked example

  • Consider pattern `ababaca`.
  • When a mismatch happens after matching `ababa`, you do not restart at pattern index `0` blindly.
  • You fall back to the longest border already known for the matched prefix.
  • That reuses overlap such as `aba`, which is why KMP keeps the scan efficient.

Common mistakes

How to recognize this kind of problem

Start practice