Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP
KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed?
KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed?
def lps(p):
l = [0] * len(p); k = 0
for i in range(1, len(p)):
while k and p[i] != p[k]: k = l[k - 1]
if p[i] == p[k]: k += 1
l[i] = k
return l
print(lps("aaabaaaabb"))- A. [0, 1, 2, 1, 0, 2, 3, 3, 4, 0]
- B. [0, 1, 2, 0, 1, 2, 3, 1, 0, 0]
- C. [0, 1, 2, 0, 1, 3, 2, 3, 4, 0]
- D. [0, 1, 2, 0, 1, 2, 3, 3, 4, 0]
Correct answer: D. [0, 1, 2, 0, 1, 2, 3, 3, 4, 0]
On a mismatch k falls back to lps[k − 1] (not straight to 0), which keeps partial matches alive. Result: [0, 1, 2, 0, 1, 2, 3, 3, 4, 0].
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A sorted array was rotated to give [58, 67, 70, 71, 77, 3, 12, 14, 55]. Binary search finds the index of the minimum: while lo < hi, mid =…
- A string s has length n. What is the time complexity of building s by repeated concatenation s = s + c in a language with immutable…
- What does this loop-counting code print? (Python) python n, c = 10, 0 for i in range(n): for j in range(i + 1, n): for k in range(j + 1…
- Over all left rotations of [5, 1, 5, 3, 9, 4], what is the maximum value of Σ i·a[i] (0-based)? (Use R(j) = R(j − 1) + sum − n·a[n − j] to…
- Items K, L, M, N, O, P are pushed onto an empty stack in this order, and a pop may happen at any time. Which pop order is NOT possible?
- Keys 121, 29, 37, 91, 13, 33, 39 are inserted in this order into an empty table of size 13 by double hashing: h1(k) = k mod 13, h2(k) = 7…