Data Structures & AlgorithmsHardGATE CS · DSA

Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed?

Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed?
s = "abaabaaba"
z = [0] * len(s)
for i in range(1, len(s)):
    while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]: z[i] += 1
print(z, sum(z))
  1. A. [0, 0, 1, 6, 0, 1, 3, 1, 0] 12
  2. B. [0, 1, 0, 6, 0, 1, 3, 0, 1] 12
  3. C. [0, 0, 1, 6, 0, 1, 3, 0, 1] 12
  4. D. [0, 0, 1, 6, 0, 1, 3, 0, 1] 6

Correct answer: C. [0, 0, 1, 6, 0, 1, 3, 0, 1] 12

Each z[i] counts how far s[i:] agrees with the start of s. Output: [0, 0, 1, 6, 0, 1, 3, 0, 1] 12.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic