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?- A. 1 1
- B. 1 2
- C. 2 2
- 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
- Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix'). python def happy(s): p = [0] len(s); k = 0 for i…
- Problem: Generate the 'look-and-say' sequence starting from '1'. python def nxt(s): out, i = [], 0 while i < len(s): j = i while j <…
- Problem: Print a matrix in spiral order. python def spiral(m): res = [] while m: res += m.pop(0) m = [list(r) for r in zip(m)][::-1]…
- Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with…
- In the Tower of Hanoi with 5 discs and 3 pegs A, B, C in a row, moves are allowed only between ADJACENT pegs (A↔B, B↔C, never A↔C…
- Problem: Count the integers in [1, 1000] that are coprime to 1000. python from math import gcd print(sum(1 for i in range(1, 1001) if…