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?
- A. Check all pairs with nested loops, about 5 x 10^9 steps
- B. Sort the array, then use two pointers from both ends
- C. Compute the sum of all pairs, about 5 x 10^9 steps
- 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
- A recursive function is called with depth 10^6 in C on a typical 8 MB stack with 64-byte frames. Is this safe?
- A bit set of 64 flags is packed in one unsigned long long. Which expression tests flag 17?
- What is the first printed value of this loop? for (int i = 3; i > 0; i--) printf("%d", i);
- int x = 0; while (x < 3) x = x + 1; printf("%d", x); What is printed?
- int count = 0; for (char c = 'a'; c <= 'z'; c++) if (c != 'e' && c != 'i' && c != 'o' && c != 'u') count++; printf("%d", count); What is…
- printf("%d", 3 > 2 ? 'Y' : 'N'); What is printed?