Data Structures & AlgorithmsVery hardProduct company OA
Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches, fallbacks) for three texts?
Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches, fallbacks) for three texts?
def kmp_steps(t, 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
k = steps = found = 0
for ch in t:
while k and ch != p[k]: k = pi[k - 1]; steps += 1
if ch == p[k]: k += 1
if k == len(p): found += 1; k = pi[k - 1]
return found, steps
print(kmp_steps("aaaaaaaaab", "aaab"), kmp_steps("a" * 1000, "aaab"), kmp_steps("ab" * 500, "aab"))What is printed?- A. (1, 6) (0, 3000) (0, 500)
- B. (1, 3) (0, 997) (0, 1000)
- C. (2, 6) (0, 997) (0, 0)
- D. (1, 6) (0, 997) (0, 500)
Correct answer: D. (1, 6) (0, 997) (0, 500)
Each fallback strictly decreases k, and k grows by at most 1 per text character, so total fallbacks ≤ number of characters – the amortised argument behind KMP's O(n + m). For 'a'×1000 vs 'aaab', every position after the first three reaches k = 3 and falls back once: 997. For (ab)×500 vs 'aab' each 'b' after an 'a' causes one fallback: 500. A naive matcher would need up to ~4 comparisons per position, i.e. O(nm).
More Coding Interview Problems questions
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…
- Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a…
- Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links…
- Problem: A drone must fly every route leg exactly once starting at P, choosing the alphabetically smallest destination whenever possible…
- Problem: Assign interns to projects; intern u may take only projects in adj[u], each project at most one intern. Maximum bipartite…
- Problem: For every warehouse in a tree network, compute the sum of distances to all other warehouses with two passes (rerooting)…