Data Structures & AlgorithmsVery hardProduct company OA
A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed?
A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed?
def prefix(p):
pi = [0] * len(p)
for i in range(1, len(p)):
k = pi[i - 1]
while k and p[i] != p[k]: k = pi[k - 1]
if p[i] == p[k]: k += 1
pi[i] = k
return pi
def count(t, p):
pi, k, c = prefix(p), 0, 0
for ch in t:
while k and ch != p[k]: k = pi[k - 1]
if ch == p[k]: k += 1
if k == len(p): c += 1; k = pi[k - 1]
return c
print(prefix("abaabab"), count("abaababaabaabab", "abaab"))- A. [0, 0, 1, 1, 2, 3, 2] 2
- B. [0, 0, 1, 1, 2, 1, 2] 3
- C. [0, 0, 1, 0, 2, 3, 2] 3
- D. [0, 0, 1, 1, 2, 3, 2] 3
Correct answer: D. [0, 0, 1, 1, 2, 3, 2] 3
pi[i] is the length of the longest proper prefix of p[0..i] that is also its suffix. For abaabab: a b → 0 0, aba → 1, abaa → 1 (fall back from 'ab' to 'a'), abaab → 2, abaaba → 3, abaabab → after the mismatch fall back 3 → 1 → then 'ab' → 2. After a full match the matcher resumes from pi[m − 1] = 2 instead of 0, so overlapping matches are found: 'abaab' starts at 0, 5 and 8 → 3. Resetting k to 0 after a match finds only the non-overlapping ones.
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
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…
- Largest rectangle under a histogram using a stack of (start index, height). What is printed? python def rect(h): st, best = [], 0 for i, x…
- Rain water trapped between bars, computed with two pointers. What is printed? python def water(h): l, r, lm, rm, w = 0, len(h) - 1, 0, 0…
- Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed? python def…