ProgrammingModerateTCS CodeVita · Infosys HackWithInfy

A program must answer 10^5 range-sum queries over an array of 10^5 numbers in CPython. Which approach is fastest?

  1. A. Call sum(a[l:r]) for each query, which is O(n) per query
  2. B. Build prefix sums once, then answer each query in O(1)
  3. C. Sort the queries and the array together for each query
  4. D. Build a new set for each query and add the range values

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

A prefix-sum array costs O(n) to build and gives each range sum as pre[r] - pre[l-1] in O(1). Slicing per query costs O(n), which is about 10^10 steps overall.

More Python Programming questions

Exams that ask this topic