Range Sum Queries on a Mutating Snapshot
Arrays & HashingAuto-graded · 15 test casesLast 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^41 <= len(queries) <= 20000 <= l <= r <= len(nums) - 1for 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).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Intuition
Answering each query [l, r] by summing nums[l..r] naively takes O(r − l + 1) time. With up to 2,000 queries on an array of up to 2,000 elements, this is at most O(n × q) = O(4,000,000) operations — acceptable for this size, but the prefix sum technique reduces each query to O(1) after a single O(n) setup pass, which is the pattern being practiced here.
Algorithm
- Build a prefix array
prefixof lengthn + 1, whereprefix[0] = 0andprefix[i] = nums[0] + nums[1] + … + nums[i-1]fori >= 1. - Answer each query
[l, r]asprefix[r + 1] - prefix[l]. This works because:prefix[r + 1]= sum ofnums[0..r]prefix[l]= sum ofnums[0..l-1]- Their difference = sum of
nums[l..r]✓
Correctness
The prefix sum identity sum(l..r) = prefix[r+1] - prefix[l] is a standard telescoping result. Edge cases:
- A single-element query
[i, i]→prefix[i+1] - prefix[i] = nums[i]✓ - Negative values work fine; prefix sums handle them without modification.
Complexity
| Time | Space | |
|---|---|---|
| Build prefix array | O(n) | O(n) |
| Answer q queries | O(q) | O(1) extra |
| Total | O(n + q) | O(n) |
Reference Solution
def range_sum_queries(nums: list, queries: list) -> list:
n = len(nums)
# Build prefix sum array of length n+1; prefix[0] = 0
prefix = [0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + nums[i]
result = []
for l, r in queries:
result.append(prefix[r + 1] - prefix[l])
return result