Data Structures & AlgorithmsVery hardProduct company OA
Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo 2⁶⁴), with a fixed odd base B. Which statement is correct?
- A. Overflow modulo 2⁶⁴ is equivalent to a random 64-bit hash, so the collision probability is about n²/2⁶⁴ for every input
- B. Collisions are impossible because 2⁶⁴ is larger than the number of distinct strings of length ≤ 10⁶
- C. There is a known family of strings (built from the Thue–Morse sequence) whose different halves collide for every odd base modulo 2⁶⁴, so the solution can be broken; using a large prime modulus with a random base avoids it
- D. Choosing an even base B would make the hash collision-free
Correct answer: C. There is a known family of strings (built from the Thue–Morse sequence) whose different halves collide for every odd base modulo 2⁶⁴, so the solution can be broken; using a large prime modulus with a random base avoids it
Modulo 2ᵏ, (Bᵗ − 1) has many factors of 2 for odd B, and the Thue–Morse strings S and its complement have hash difference ∏(B^(2ⁱ) − 1), which is divisible by 2⁶⁴ once the length is about 2¹¹ – for EVERY odd base. So the 'random hash' argument fails: the input is adversarial and the modulus is fixed. An even base is worse (high powers become 0, ignoring early characters). Pigeonhole guarantees collisions exist anyway. A prime modulus around 10⁹ – 10¹⁸ with a base chosen at random at runtime (or two moduli) restores the probabilistic guarantee.
More Coding Interview Problems questions
- Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is…
- Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts…
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…
- Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all…
- Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time…
- Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a…