GATE Computer ScienceHardGATE CS (PYQ pattern)

The Z-array of a string s has Z[i] = length of the longest common prefix of s and s[i..]. (Z[0] is taken as 0.) What is the sum of all Z values of s = aaabaaaab?

  1. A. 11
  2. B. 15
  3. C. 13
  4. D. 17

Correct answer: C. 13

Z = [0, 2, 1, 0, 3, 4, 2, 1, 0], and the sum is 13. For example Z[4] = 3 because aaaab matches the prefix aaab for three characters and then fails, while Z[5] = 4 because s[5..] = aaab equals the prefix aaab.

More Algorithms questions

Exams that ask this topic