Range Sum Queries

Prefix Sums Arrays Query Cumulative Sum

Problem Description

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.

Example

For the input:

  • nums = [1, 2, 3, 4, 5]
  • queries = [[1, 3], [0, 4], [2, 2]]

The output should be:

  • For query [1, 3]: sum is 2 + 3 + 4 = 9
  • For query [0, 4]: sum is 1 + 2 + 3 + 4 + 5 = 15
  • For query [2, 2]: sum is 3

Thus, the function should return [9, 15, 3].

Function Signature

function rangeSumQueries(nums, queries) {
    // Your code here
}

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= queries.length <= 10^5
  • Each query contains valid indices with 0 <= i <= j < nums.length

Note

On December 3, many developers celebrate progress and problem solving. Enjoy this challenge and keep coding!