Data Structures & AlgorithmsVery hardICPC regional · String round

Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:], with z[0] set to 0) for s = 'aabxaab'.

Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:], with z[0] set to 0) for s = 'aabxaab'.
def z(s):
    n = len(s)
    z = [0] * n
    l = r = 0
    for i in range(1, n):
        if i < r:
            z[i] = min(r - i, z[i - l])
        while i + z[i] < n and s[z[i]] == s[i + z[i]]:
            z[i] += 1
        if i + z[i] > r:
            l, r = i, i + z[i]
    return z
print(z('aabxaab'))
What is printed?
  1. A. [0, 1, 0, 0, 3, 1, 0]
  2. B. [7, 1, 0, 0, 3, 1, 0]
  3. C. [0, 0, 0, 0, 3, 1, 0]
  4. D. [0, 1, 0, 0, 3, 2, 0]

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

The Z-algorithm reuses a matched box [l, r) to skip work. The prefix 'aab' recurs at index 4, giving z[4] = 3, and z[5] = 1 because 'ab' matches only 'a'.

More Coding Interview Problems questions

Exams that ask this topic