Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious hits.

Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious hits.
def rk(text, pat):
    m = len(pat); hp = sum(map(ord, pat)); h = sum(map(ord, text[:m]))
    true = spur = 0
    for i in range(len(text) - m + 1):
        if i: h += ord(text[i + m - 1]) - ord(text[i - 1])
        if h == hp:
            if text[i:i+m] == pat: true += 1
            else: spur += 1
    return true, spur
print(*rk("abcdcbadcb", "bcd"))
What is printed?
  1. A. 1 1
  2. B. 1 2
  3. C. 2 2
  4. D. 3 0

Correct answer: B. 1 2

The pattern's sum matches every window that is a permutation of b, c, d: 'bcd' (true) and 'dcb' twice (spurious); 'bad' and 'adc' have different sums. So 1 true match and 2 spurious hits. A polynomial rolling hash makes such collisions rare.

More Coding Interview Problems questions

Exams that ask this topic