Data Structures & AlgorithmsVery hardProduct company OA

Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed?

Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed?
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
s = "aabcaabxaab"
zz = z(s)
print(zz, sum(1 for i in range(1, len(s)) if zz[i] >= 3))
  1. A. [0, 1, 0, 0, 3, 1, 0, 0, 2, 1, 0] 2
  2. B. [0, 1, 0, 0, 4, 1, 0, 0, 3, 1, 0] 3
  3. C. [0, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0] 2
  4. D. [0, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0] 3

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

s = aabcaabxaab. Position 4 starts 'aabx…' which matches 'aabc' for 3 characters; position 8 starts 'aab' and the string ends, so 3. Inside the box [l, r) the algorithm copies z[i − l] capped at r − i, which is what keeps it O(n). Exactly two positions (4 and 8) have z ≥ 3, i.e. two occurrences of the 3-character prefix 'aab' after the start. z[0] is conventionally 0 (or n).

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

Exams that ask this topic