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?- A. [0, 2, 1, 0, 3, 1, 0]
- B. [0, 2, 1, 0, 2, 2, 0]
- C. [0, 2, 1, 0, 2, 1, 0]
- 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
- Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet…
- Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be…
- Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have…
- Problem: From index 0, a[i] is the longest jump allowed from i. Find the minimum number of jumps to reach the last index (greedy BFS by…
- Problem: Split a string into as many parts as possible so that each letter appears in at most one part; return the part sizes. python def…
- How many structurally different binary search trees can be built on the keys 1..7 if the ROOT must be 3?