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"))- A. (1, 1)
- B. (1, 0)
- C. (2, 1)
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…
- Largest rectangle under a histogram using a stack of (start index, height). What is printed? python def rect(h): st, best = [], 0 for i, x…
- Rain water trapped between bars, computed with two pointers. What is printed? python def water(h): l, r, lm, rm, w = 0, len(h) - 1, 0, 0…
- Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed? python def…
- Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such…
- A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros…