ProgrammingHard

For n = 10^5, which expression correctly counts the pairs (i, j) with i < j where a[i] + a[j] equals a target, in O(n log n) time?

  1. A. Check all pairs with nested loops, about 5 x 10^9 steps
  2. B. Sort the array, then use two pointers from both ends
  3. C. Compute the sum of all pairs, about 5 x 10^9 steps
  4. D. Compare each element with the whole array twice, about 10^10 steps

Correct answer: B. Sort the array, then use two pointers from both ends

Sorting costs O(n log n), and the two-pointer scan is O(n). The nested loops are too slow at 5 x 10^9 steps.

More C Programming questions

Exams that ask this topic