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 = "bbaaaabab"
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, 1, 0, 0, 0, 0, 1, 0, 1] 1
  2. B. [0, 1, 0, 0, 0, 0, 1, 0, 1] 3
  3. C. [0, 1, 0, 0, 0, 0, 0, 1, 1] 3
  4. D. [1, 0, 0, 0, 0, 0, 1, 0, 1] 3

Correct answer: B. [0, 1, 0, 0, 0, 0, 1, 0, 1] 3

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

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

Exams that ask this topic