Data Structures & AlgorithmsVery hardGATE CS · DSA
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("aabbbabaaa"))- A. [0, 1, 0, 0, 0, 1, 0, 1, 2, 2]
- B. [0, 0, 1, 0, 0, 1, 0, 1, 2, 2]
- C. [0, 1, 0, 0, 0, 0, 1, 1, 2, 2]
- D. [0, 1, 0, 0, 0, 1, 0, 1, 2, 1]
Correct answer: A. [0, 1, 0, 0, 0, 1, 0, 1, 2, 2]
On a mismatch k falls back to lps[k − 1] (not straight to 0), which keeps partial matches alive. Result: [0, 1, 0, 0, 0, 1, 0, 1, 2, 2].
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
- Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print? python def add(a, b): d…
- A monotonic deque reports the maximum of every window of size 3 in [14, 5, −3, 14, 5, 14, −5, 16, 4]. What is the SUM of all reported…
- Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than…
- Which data structure gives O(1) worst-case time for inserting and deleting at BOTH ends and also O(1) access by index?
- What is the length of the shortest contiguous subarray of [1, 3, 5, 6, 3, 3, 7, 9, 4, 9] whose sum is at least 20? (All values are…
- Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed? python from collections import defaultdict a = [1…