KatInterview

Range Sum Queries on a Mutating Snapshot

Arrays & HashingAuto-graded · 15 test cases
EasyAuto-gradedArrays & Hashingarraysprefix sumshashing

Last updated

Tests ability to use prefix sums to efficiently answer multiple range-sum queries on a fixed array.

Range Sum Queries on a Snapshot

You are given a list of integers nums and a list of queries. Each query is a pair [l, r] representing a closed interval (both endpoints inclusive). For each query, return the sum of all elements in nums from index l to index r.

Return a list of integers, one answer per query, in the same order as the queries.

Constraints

  • 1 <= len(nums) <= 2000
  • -10^4 <= nums[i] <= 10^4
  • 1 <= len(queries) <= 2000
  • 0 <= l <= r <= len(nums) - 1 for every query [l, r]
  • All indices are zero-based.

Examples

Example 1

Input: range_sum_queries([1, 2, 3, 4, 5], [[0, 4], [1, 3], [2, 2]])

Output: [15, 9, 3]

Example 2

Input: range_sum_queries([10, -3, 7, 0, -5, 2], [[0, 5], [2, 4], [3, 3]])

Output: [11, 2, 0]

Example 3

Input: range_sum_queries([-1, -2, -3], [[0, 2], [1, 2]])

Output: [-6, -5]

Hints

Hint 1

Build a prefix sum array P where P[i] holds the sum of nums[0..i-1]; this lets you answer any range sum in O(1).

Hint 2

The sum of nums[l..r] equals P[r+1] - P[l], where P is the prefix sum array of length len(nums)+1.

Hint 3

Precompute the prefix array once in O(n), then answer all queries in O(1) each — total O(n + q).