Static Array Range Sum Queries
Arrays & HashingAuto-graded · 19 test casesLast updated
Process a sequence of range sum queries on an immutable array efficiently using prefix sums.
Given an integer array nums and a sequence of range queries, return the sum of the elements for each specified range query.
You are given:
- An initial list of integers
nums. - A list of operation names
operations. - A matching list of argument pairs
arguments.
For each query operation in operations named "sumRange", the corresponding entry in arguments is a pair of indices [left, right]. Calculate the sum of the subarray from index left to right inclusive (i.e., $\sum_{k=left}^{right} \text{nums}[k]$).
If an operation in operations is not "sumRange" (such as constructor calls), the output for that operation position should be None (represented as null in JSON).
Your solution should be optimized to answer multiple range sum queries efficiently.
Constraints
- $1 \le \text{len}(nums) \le 10^5$
- $-10^4 \le nums[i] \le 10^4$
- $1 \le \text{len}(operations) \le 10^5$
- $\text{len}(operations) == \text{len}(arguments)$
- For each
"sumRange"query, $0 \le left \le right < \text{len}(nums)$.
Examples
Example 1
Input: range_sum_query([-2, 0, 3, -5, 2, -1], [17, 17, 17], [[0, 2], [2, 5], [0, 5]])
Output: [None, None, None]
Hints
Hint 1
Iterating through the range [left, right] for every query takes O(N) per query, which will be too slow for many operations.
Hint 2
Can you precompute running totals so that any subarray sum can be calculated in O(1) time?
Hint 3
Compute an array `prefix` of size N + 1 where `prefix[k]` stores the sum of the first `k` elements. How can `prefix[right + 1]` and `prefix[left]` give you the subarray sum?
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A naive implementation sums the elements from left to right individually for each query. In the worst case, a single query takes $O(N)$ time, leading to $O(N \cdot Q)$ total time for $Q$ queries. With $N, Q \le 10^5$, this approach will time out.
Since the array nums is static and does not change between queries, we can preprocess the array into a Prefix Sum array in $O(N)$ time.
We construct a prefix sum array prefix of length $N + 1$ such that:
prefix[0] = 0prefix[k] = nums[0] + nums[1] + ... + nums[k-1]for $k > 0$
Using this structure, the sum of elements from index left to right (inclusive) can be computed in $O(1)$ time as:
$$\text{sum}(left, right) = \text{prefix}[right + 1] - \text{prefix}[left]$$
Using a size $N + 1$ array with a leading zero avoids special checks for when left == 0.
Complexity
- Preprocessing Time: $O(N)$ to compute the prefix sums.
- Query Time: $O(1)$ per query.
- Total Time Complexity: $O(N + Q)$, where $N$ is the length of
numsand $Q$ is the number of operations. - Space Complexity: $O(N)$ auxiliary space to store the prefix sum array.
Implementation
from typing import List, Optional
def range_sum_query(nums: List[int], operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
prefix = [0] * (len(nums) + 1)
for index, val in enumerate(nums):
prefix[index + 1] = prefix[index] + val
results = []
for op, args in zip(operations, arguments):
if op == "sumRange":
left, right = args[0], args[1]
results.append(prefix[right + 1] - prefix[left])
else:
results.append(None)
return results