Given an integer array nums
and an array of queries where each query is represented by a pair of indices [i, j]
(using 0-based indexing), write a function that returns an array of integers representing the sum of the subarray from index i
to j
(inclusive) for each query. To achieve this efficiently, precompute the prefix sums of the array and use them to answer queries in constant time.
For the input:
nums = [1, 2, 3, 4, 5]
queries = [[1, 3], [0, 4], [2, 2]]
The output should be:
[1, 3]
: sum is 2 + 3 + 4 = 9
[0, 4]
: sum is 1 + 2 + 3 + 4 + 5 = 15
[2, 2]
: sum is 3
Thus, the function should return [9, 15, 3]
.
function rangeSumQueries(nums, queries) {
// Your code here
}
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= queries.length <= 10^5
0 <= i <= j < nums.length
On December 3, many developers celebrate progress and problem solving. Enjoy this challenge and keep coding!