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?
  1. A. (2, 2) (2, 1)
  2. B. (3, 0) (2, 0)
  3. C. (2, 0) (2, 0)
  4. 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

Exams that ask this topic