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

Problem: Support 'add number' and 'find a pair summing to t' where adds are 10⁵ and finds are rare, versus the opposite workload. Which statement is correct?

  1. A. A sorted array is optimal for both workloads
  2. B. A heap gives O(1) for both operations
  3. C. The two workloads need the same structure
  4. D. Frequent adds: keep a hash map of counts (O(1) add, O(n) find); frequent finds: keep a set of all pair sums (O(n) add, O(1) find)

Correct answer: D. Frequent adds: keep a hash map of counts (O(1) add, O(n) find); frequent finds: keep a set of all pair sums (O(n) add, O(1) find)

This is a design trade-off: whichever operation dominates should be O(1). With counts, find scans each value and checks t − x (handling x = t − x needing count ≥ 2). Precomputing all pair sums makes add O(n) but find O(1).

More Coding Interview Problems questions

Exams that ask this topic