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?
- A. Check every pair with nested loops, about 2 x 10^10 steps
- B. Call bsearch for every element on the same array, about O(n^2 log n)
- C. Sort the array inside each loop iteration, O(n^2 log n)
- 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
- For N = 10^6 integers in the range 0 to 10^6, which sorting method is correct and fast enough?
- A queue is needed for 10^5 operations on an array. Which dequeue is correct and fast enough?
- Growing a dynamic array by a fixed 1 element every time it fills (capacity + 1) costs what in the worst case for N pushes?
- Which method is correct and fast enough for answering 10^5 range-sum queries on an array of 10^5 integers?
- Which method is correct and fast enough for n choose r modulo p = 10^9 + 7 for 10^6 queries with n up to 10^6?
- To compute the sum of 1 through n = 10^9 without overflow in C, which code is correct?