Given an integer array nums and an array of range queries queries, where each query is a pair [left, right], return an array answer such that answer[i] is the sum of the elements of nums between indices left and right inclusive.
You must answer each query in constant time after an initial linear-time preprocessing step using the prefix sum technique.
Function Signature
def range_sum_queries(nums: list[int], queries: list[list[int]]) -> list[int]:
Rules
-
Each query is a pair
[left, right]
of 0-based indices, and both
nums[left]
and
nums[right]
are included in the sum.
-
answer[i]
is the result for
queries[i]
, so the output has the same length and order as
queries
.
Constraints
-
1 <= nums.length <= 10⁴
-
-10⁵ <= nums[i] <= 10⁵
-
0 <= left <= right < nums.length
-
1 <= queries.length <= 10⁴
Examples
Input: nums = [1, 2, 3, 4, 5], queries = [[0, 2], [1, 4], [0, 4], [2, 2]]
Output: [6, 14, 15, 3]
The sums are 1 + 2 + 3 = 6, then 2 + 3 + 4 + 5 = 14, then the whole array 1 + 2 + 3 + 4 + 5 = 15. The last query covers the single element nums[2] = 3.
Input: nums = [-2, 0, 3, -5, 2, -1], queries = [[0, 2], [2, 5], [0, 5]]
Output: [1, -1, -3]
The sums are -2 + 0 + 3 = 1, then 3 + (-5) + 2 + (-1) = -1, and the whole array sums to -3. Negative values need no special handling.