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?
- A. Compare characters per query – O(1) each
- B. Polynomial rolling hash with prefix hashes – O(n) preprocessing, O(1) per query (with a large modulus or double hashing)
- C. KMP per query – O(1) each
- 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
- Problem: n ≤ 40 items with weights up to 10⁹; count subsets with total weight ≤ W. Why is meet-in-the-middle preferred here?
- Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?
- Problem: A grid of R × C = 10³ × 10³ heights; find the minimum possible 'maximum step height' along any path from top-left to…
- Problem: Count distinct values in every window of size k over n = 10⁶ values. What is the optimal complexity?
- Problem: n = 10⁵ cities connected by roads that are added one at a time; after each addition report the number of connected components…
- Problem: Find the longest substring that appears at least twice in a string of length 10⁵. Which approach is efficient?