Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0).

Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0).
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("aaabaab"))
What is printed?
  1. A. [0, 2, 1, 0, 3, 1, 0]
  2. B. [0, 2, 1, 0, 2, 2, 0]
  3. C. [0, 2, 1, 0, 2, 1, 0]
  4. D. [0, 1, 1, 0, 2, 1, 0]

Correct answer: C. [0, 2, 1, 0, 2, 1, 0]

From index 4, 'aab' matches the prefix 'aaa' only for 'aa' (the third character b ≠ a), so z[4] = 2, and z[5] = 1. z[1] = 2 because 'aab…' matches 'aa' of the prefix before b ≠ a.

More Coding Interview Problems questions

Exams that ask this topic