fenwick tree

Z function

At each index ii after zero, compare the string starting at ii with the start of SS. Count how many characters match before they differ or you reach the end. By convention, Z[0]=0Z[0] = 0.

Index 0 1 2 3 4 5 6
S[i]S[i] a a a b a a b
Z[i]Z[i] 0 2 1 0 2 1 0

At i=4i = 4, compare aab with the start of SS. The first two characters match, but the third differs, so Z[4]=2Z[4] = 2.

Implementation

vector<int> z_function(string const& S) {
  int N = S.size();
  vector<int> z(N);
  int l = 0, r = 0;
  for (int i = 1; i < N; i++) {
    if (i < r) z[i] = min(r-i, z[i-l]);
    while (i + z[i] < N && S[z[i]] == S[i+z[i]]) z[i]++;
    if (i + z[i] > r) {
      l = i;
      r = i+z[i];
    }
  }
  return z;
}

Interface

Operation Description Time
z_function(S) Returns the array ZZ for the string S of length NN. O(N){O(N)}

Problems