Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count (possibly overlapping) occurrences of a pattern in a text with KMP.
Problem: Count (possibly overlapping) occurrences of a pattern in a text with KMP.
def kmp_count(t, p):
f = [0] * len(p); k = 0
for i in range(1, len(p)):
while k and p[i] != p[k]: k = f[k-1]
if p[i] == p[k]: k += 1
f[i] = k
cnt = k = 0
for c in t:
while k and c != p[k]: k = f[k-1]
if c == p[k]: k += 1
if k == len(p): cnt += 1; k = f[k-1]
return cnt
print(kmp_count("aaaaaaa", "aaaa"), kmp_count("abababab", "abab"))What is printed?- A. 4 3
- B. 1 2
- C. 4 2
- D. 7 4
Correct answer: A. 4 3
After a full match KMP falls back to f[m − 1] instead of 0, so overlapping matches are kept: 'aaaa' starts at indices 0–3 of a 7-letter run (4 matches) and 'abab' at 0, 2, 4 (3 matches). str.count would give 1 and 2 because it skips past each match.
More Coding Interview Problems questions
- Problem: Count DISTINCT palindromic substrings by expanding around centres and collecting them in a set. python def distinctpal(s): seen =…
- Problem: Build the suffix array of a string (start indices of suffixes in sorted order) and its LCP array (Kasai's algorithm). python def…
- Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially)…
- Problem: Point-update / range-maximum segment tree (iterative, size n = 8). python n = 8; t = [0] (2 n) def upd(i, v): i += n; t[i] = v…
- Mo's algorithm answers q offline range queries on an array of n elements by sorting queries into √n-sized blocks of their left ends. If…
- Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with…