Data Structures & AlgorithmsVery hardProduct company OA

You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?

  1. A. Nested loops over all pairs – about 2·10¹⁰ simple additions finish within 1 s in C++
  2. B. A hash map of complements as in two-sum, since a hash lookup answers '≤ T' in O(1)
  3. C. Prefix sums of the sorted array, since the number of valid pairs equals the prefix sum at index T
  4. D. Sort, then two pointers: for each left index move the right pointer down while the sum exceeds T and add (right − left) – O(n log n)

Correct answer: D. Sort, then two pointers: for each left index move the right pointer down while the sum exceeds T and add (right − left) – O(n log n)

After sorting, if a[l] + a[r] ≤ T then every partner l + 1..r works for l, so each step either fixes l's count or discards r – both pointers move at most n times. n²/2 = 2·10¹⁰ pairs is ~100× too many for 1 s. A hash map answers equality queries only, not ranges. Prefix sums of VALUES say nothing about pair counts, and T is a value, not an index. Note that the answer can reach ~2·10¹⁰, so it needs a 64-bit counter.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic