Katkat

Solve two-sum variants at scale

AmazonData Scientist · Onsite

Last updated

This question evaluates array and hashing algorithms, pair-sum reasoning including duplicate handling and lexicographic minimality, streaming and external-memory algorithm design, trade-offs in time/space complexity, and extension to three-sum with deduplication.

Base task: Given nums = [3, 1, 2, 2, 4] and target = 4, return the 0-based index pair (i, j) with i < j such that nums[i] + nums[j] = target. If multiple pairs exist, return the lexicographically smallest (i, j). Achieve expected O(n) time and O(n) extra space; justify correctness for duplicates. Follow-ups:

  1. If nums is already sorted ascending, provide an O(n) time, O(1) space solution and prove minimal lexicographic pair selection still holds.
  2. Streaming variant: nums arrives as an unbounded stream and you must answer membership queries two_sum_exists(x) online with sublinear memory. Propose a data structure, update/query costs, and false-positive/false-negative trade-offs if any.
  3. Very large array (hundreds of millions of ints) under a 200MB RAM cap. Describe an external-memory or hashing-with-bucketing approach, handling negatives and overflow.
  4. Extend to three-sum for a sorted array; give complexity and deduplication strategy.