ProgrammingModerateAmazon OA · Flipkart coding round

Which technique gives the lowest total cost for answering q range-sum queries on a fixed Python list of length n, where n and q are both 2 * 10^5?

  1. A. Sort the list before each query so that bisect can answer the sum
  2. B. Keep the list as a set and use len() to get the sum of elements
  3. C. Build a prefix-sum list once in O(n), then answer each query in O(1) by subtracting two prefix values
  4. D. Call sum(a[l:r]) for each query, because slicing is O(1)

Correct answer: C. Build a prefix-sum list once in O(n), then answer each query in O(1) by subtracting two prefix values

Prefix sums cost O(n) to build and O(1) per query, for O(n + q) total. Slicing copies the elements, so sum(a[l:r]) costs O(r - l) per query.

More Python Programming questions

Exams that ask this topic