Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it.
Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it.
s="abacabab"
pi=[0]*len(s)
for i in range(1,len(s)):
j=pi[i-1]
while j>0 and s[i]!=s[j]: j=pi[j-1]
if s[i]==s[j]: j+=1
pi[i]=j
print(sum(pi))What is printed?- A. 7
- B. 9
- C. 6
- D. 3
Correct answer: B. 9
The failure function falls back through earlier borders with pi[j-1] rather than jumping to zero. Dropping the fallback loses shorter borders, using the reversed string changes every border, and the maximum is a different statistic from the sum.
More Coding Interview Problems questions
- A directed weighted graph has edges 0→1 (2), 0→2 (2), 1→3 (1), 2→3 (1), 1→4 (4), 2→4 (5), 3→4 (3), 3→5 (4), 4→5 (1). Count the number of…
- On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3…
- A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all…
- Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and…
- Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in…
- Find the sum of the maximum of every window of length 3 in a = [1, 3, −1, −3, 5, 3, 6, 7] (windows slide one step at a time). python…