fenwick tree

Prefix function

At index ii, look only at the prefix of SS ending at ii. Then π[i]\pi[i] is the length of its longest suffix that is also a prefix. The whole substring doesn’t count.

Index 0 1 2 3 4 5 6
S[i]S[i] a b a c a b a
π[i]\pi[i] 0 0 1 0 1 2 3

At i=4i = 4, look at abaca. It starts and ends with a, and nothing longer matches both ends except abaca itself, so π[4]=1\pi[4] = 1.

Implementation

vector<int> prefix_function(string const& S) {
  int N = S.size();
  vector<int> pi(N);
  for (int i = 1; i < N; i++) {
    int j = pi[i-1];
    while (j > 0 && S[i] != S[j]) j = pi[j-1];
    if (S[i] == S[j]) j++;
    pi[i] = j;
  }
  return pi;
}

Interface

Operation Description Time
prefix_function(S) Returns the array π\pi for the string S of length NN. O(N){O(N)}

Further reading

The Automaton Interpretation for the KMP Algorithm