ProgrammingModerate
Binary search on the answer: a monotone check runs in O(n) and the answer lies in [1, 10^9]. What is the total complexity?
- A. O(n^2), since each check is a nested loop
- B. O(10^9) because the answer range is scanned linearly
- C. O(n log n), since the array is sorted first
- D. O(n log(10^9)), about 30 checks of O(n) each
Correct answer: D. O(n log(10^9)), about 30 checks of O(n) each
log2(10^9) is about 30, so the search performs about 30 checks, each linear. The answer range is never scanned one value at a time.
More C Programming questions
- A recursive naive Fibonacci fib(n) makes calls(n) = calls(n-1) + calls(n-2) + 1 with calls(0) = calls(1) = 1. Roughly how many calls does…
- A loop computes the number of decimal digits of n = 10^18 with while (n) { n /= 10; cnt++; }. What value does cnt reach?
- Trial division factorises a number up to 10^12 with for (i = 2; i i <= n; i++) while (n % i == 0) n /= i;. About how many outer iterations…
- A 2 x 2 matrix is raised to the power 10^18 by repeated squaring. How many squaring steps are needed?
- Which statement about the nested loop for (i = 0; i < n; i++) for (j = 1; j < n; j = 2) is correct?
- Which operation is O(1) in a C array, but O(n) in a singly linked list when the head is given?