ProgrammingHard

Which C code is correct and fast enough for finding whether a sorted array a of n = 2 x 10^5 ints has two elements summing to t?

  1. A. Check every pair with nested loops, about 2 x 10^10 steps
  2. B. Call bsearch for every element on the same array, about O(n^2 log n)
  3. C. Sort the array inside each loop iteration, O(n^2 log n)
  4. D. Two pointers i = 0, j = n - 1, moving i up or j down by the sum's comparison with t, O(n) after sorting

Correct answer: D. Two pointers i = 0, j = n - 1, moving i up or j down by the sum's comparison with t, O(n) after sorting

Once sorted, two pointers close in one pass, so the check is O(n). The quadratic versions make about 2 x 10^10 comparisons.

More C Programming questions

Exams that ask this topic