Data Structures & AlgorithmsHardProduct company OA

Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to find all occurrences.

Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '$' + text to find all occurrences.
def z_func(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
def occ(p, t):
    z = z_func(p + "$" + t)
    return [i - len(p) - 1 for i in range(len(z)) if z[i] == len(p)]
print(z_func("abacaba"), occ("aba", "abababa"))
What is printed?
  1. A. [0, 0, 1, 0, 3, 0, 1] [0, 2, 4]
  2. B. [0, 0, 1, 0, 3, 0, 1] [0, 4]
  3. C. [0, 0, 1, 0, 3, 2, 1] [0, 2, 4]
  4. D. [7, 0, 1, 0, 3, 0, 1] [0, 2, 4]

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

[l, r) is the rightmost window known to match a prefix; inside it z[i] starts from z[i − l] and only extends past r, so total work is O(n). "abacaba": z[4] = 3 ("aba"), z[2] = z[6] = 1. The separator '$' stops matches from crossing into the text, and every position with z = |p| is an occurrence – including overlapping ones (0, 2, 4). By convention z[0] is left 0 here.

More Coding Interview Problems questions

Exams that ask this topic