Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious hash hits (equal hash, different text).
Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious hash hits (equal hash, different text).
def rk(text, pat, base, mod):
m = len(pat); hp = ht = 0; h = pow(base, m - 1, mod); hits = spurious = 0
for i in range(m):
hp = (hp * base + ord(pat[i])) % mod; ht = (ht * base + ord(text[i])) % mod
for i in range(len(text) - m + 1):
if hp == ht:
if text[i:i + m] == pat: hits += 1
else: spurious += 1
if i + m < len(text):
ht = ((ht - ord(text[i]) * h) * base + ord(text[i + m])) % mod
return hits, spurious
print(rk("abracadabra", "abr", 10, 7), rk("abracadabra", "abr", 256, 1000003))What is printed?- A. (2, 2) (2, 1)
- B. (3, 0) (2, 0)
- C. (2, 0) (2, 0)
- D. (2, 1) (2, 0)
Correct answer: D. (2, 1) (2, 0)
The window hash is updated in O(1): remove the leaving character times base^(m−1), shift, add the new one; Python's % keeps it non-negative. With modulus 7 there are only 7 hash values, so one of the 9 windows collides with "abr" without matching – a spurious hit that the explicit string comparison rejects. A large modulus makes collisions rare. Expected O(n + m); worst case O(n·m) if every window collides.
More Coding Interview Problems questions
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…
- Problem: What is the time complexity of this nested loop, and how many inner steps run for n = 1024? python def cnt(n): c = 0 for i in…
- Problem: Find the bug: a backtracking routine collects all subsets of [1, 2]. python def subsets(a): res, path = [], [] def bt(i): if i ==…
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…