Data Structures & AlgorithmsVery hardProduct company OA

Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?

Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?
def rk(t, p, base=10, mod=7):
    m = len(p); hp = ht = 0; hi = pow(base, m - 1, mod)
    for i in range(m):
        hp = (hp * base + int(p[i])) % mod
        ht = (ht * base + int(t[i])) % mod
    hits = spurious = 0
    for i in range(len(t) - m + 1):
        if ht == hp:
            if t[i:i + m] == p: hits += 1
            else: spurious += 1
        if i + m < len(t):
            ht = ((ht - int(t[i]) * hi) * base + int(t[i + m])) % mod
    return hits, spurious
print(rk("3141592653589793", "26"))
  1. A. (1, 1)
  2. B. (1, 0)
  3. C. (2, 1)
  4. D. (1, 3)

Correct answer: A. (1, 1)

The pattern 26 has hash 26 mod 7 = 5. Sliding over 3141592653589793, the 2-digit windows whose value ≡ 5 (mod 7) are 26 (true match) and 89 (89 = 7·12 + 5, a collision), so one hit and one spurious hit that costs a full character comparison. With a tiny modulus collisions are frequent, and an adversary can make every window collide, giving O(nm); a large random prime modulus makes them rare.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic