Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A string of length n = 10⁵; answer q = 10⁵ queries 'are substrings [l1, r1] and [l2, r2] equal?'. Which technique fits?

  1. A. Compare characters per query – O(1) each
  2. B. Polynomial rolling hash with prefix hashes – O(n) preprocessing, O(1) per query (with a large modulus or double hashing)
  3. C. KMP per query – O(1) each
  4. D. A trie of all substrings – O(n) total

Correct answer: B. Polynomial rolling hash with prefix hashes – O(n) preprocessing, O(1) per query (with a large modulus or double hashing)

Prefix hashes give any substring's hash as H[r + 1] − H[l]·B^(len) mod M in O(1). Direct comparison is O(length) per query (up to 10¹⁰ total). A trie of all substrings has O(n²) nodes. Collisions are made negligible with two moduli.

More Coding Interview Problems questions

Exams that ask this topic