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?- A. [0, 1, 0, 0, 3, 1, 0]
- B. [7, 1, 0, 0, 3, 1, 0]
- C. [0, 0, 0, 0, 3, 1, 0]
- 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
- Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too). python def count(s)…
- Problem: A directed graph with V vertices is relaxed with Bellman-Ford. After V - 1 full rounds of relaxing all edges, one more round…
- Problem: A Fenwick tree of size 8 receives point adds (1,+5), (3,+2), (5,+7), (8,+1) with the usual add and prefix-query code, then prints…
- Problem: You want the maximum number of non-overlapping intervals. Which greedy rule is provably optimal?
- Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3]. python from collections import Counter def cnt(a): seen =…
- Problem: What does the following print? python print([format(i ^ (i >> 1), '03b') for i in range(4)])