Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix).
Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix).
def pi(s):
p = [0] * len(s)
for i in range(1, len(s)):
k = p[i-1]
while k and s[i] != s[k]: k = p[k-1]
if s[i] == s[k]: k += 1
p[i] = k
return p
print(pi("aabaaab"))What is printed?- A. [0, 1, 0, 1, 2, 2, 3]
- B. [0, 1, 0, 1, 2, 3, 3]
- C. [0, 1, 0, 1, 2, 2, 2]
- D. [0, 0, 0, 1, 2, 2, 3]
Correct answer: A. [0, 1, 0, 1, 2, 2, 3]
At i = 5 ('a' after 'aabaa'), k = 2 but s[5] = 'a' ≠ s[2] = 'b', so k falls back to pi[1] = 1 and then matches, giving 2 (not 3). At i = 6, s[6] = 'b' = s[2], so pi = 3: the prefix 'aab' equals the suffix 'aab'.
More Coding Interview Problems questions
- 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). python…
- 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…