ProgrammingHard
Which method is correct and fast enough for answering 10^5 range-sum queries on an array of 10^5 integers?
- A. Add the elements of each range in a loop, about 10^10 steps total
- B. Sort the array before each query, about 10^10 steps
- C. Recompute a full 2D table for every pair of indices, about 10^10 steps
- D. Build a prefix-sum array once in O(N), then answer each query in O(1) as pre[r] - pre[l - 1]
Correct answer: D. Build a prefix-sum array once in O(N), then answer each query in O(1) as pre[r] - pre[l - 1]
Prefix sums cost O(N + Q) overall. Summing each range directly costs about N x Q = 10^10 additions in the worst case.
More C Programming questions
- 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?
- Which method finds all primes up to 10^6 in time that is correct and fast enough?
- 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 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?