ProgrammingHardTCS NQT · Infosys

A program must answer 10^5 range-sum queries on an array of 10^5 ints within a 1 second limit. Which approach is fast enough?

  1. A. Recompute the sum with a loop for each query, about 10^10 steps
  2. B. Bubble-sort the array before each query
  3. C. Build prefix sums once in O(N), then answer each query in O(1)
  4. D. Use a recursion that re-sums the left half for every query

Correct answer: C. Build prefix sums once in O(N), then answer each query in O(1)

Per-query loops need about 10^10 additions, far beyond the limit. A prefix array built once answers each query with a single subtraction, for O(N + Q) total work.

More C Programming questions

Exams that ask this topic