Skip to content
Prefix/Suffix

Prefix Function

Precomputing the Pi table for optimized jumping.

Time Complexity
O(M)
Space Complexity
O(M)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 21
Building Pattern Pi
A
0
B
1
A
2
B
3
C
4
A
5
B
6
A
7
Pi Table
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
Process Description

Initialize pi[0] = 0. Starting from the second character.

Technical Guide

The Prefix Function (often called the Pi table) is the engine behind KMP. For every position in the pattern, it stores the length of the longest proper prefix that is also a suffix of that substring. This precomputation tells us exactly how much of the pattern we've already successfully matched even after a mismatch occurs, allowing us to skip ahead.

Logical Phases

  • 1
    Initializing pi[0] = 0.
  • 2
    Comparing the current character with the character after the current prefix.
  • 3
    Backtracking through previous prefix lengths on mismatch.
  • 4
    Storing the resulting lengths in an array of size M.

Implementation

if (p[k] === p[q]) k++;
pi[q] = k;

Expert Pitfalls

Incorrectly including the entire string as a 'proper' prefix (k must be less than current length).