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?- A. [0, 0, 1, 0, 3, 0, 1] [0, 2, 4]
- B. [0, 0, 1, 0, 3, 0, 1] [0, 4]
- C. [0, 0, 1, 0, 3, 2, 1] [0, 2, 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
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…
- Problem: Count the total number of 1 bits in all integers from 0 to n without iterating over them: bit b repeats a pattern of 2^b zeros…
- Problem: Minimum single-bit flips in a and b so that (a OR b) == c. python def minflips(a, b, c): flips = 0 while a or b or c: x, y, z = a…
- Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by…