ProgrammingHard

Which method is correct and fast enough for answering 10^5 range-sum queries on an array of 10^5 integers?

  1. A. Add the elements of each range in a loop, about 10^10 steps total
  2. B. Sort the array before each query, about 10^10 steps
  3. C. Recompute a full 2D table for every pair of indices, about 10^10 steps
  4. 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

Exams that ask this topic