Prefix Range Sum

Prefix Sums Arrays Queries

Problem Statement

You are given an array of integers nums of length n and a list of queries. Each query is a pair of indices (L, R) (0-indexed) that represents a range in the array. Your task is to compute the sum of the elements in nums for each query efficiently.

Example:

Let nums = [3, 1, 4, 1, 5, 9, 2] and queries = [[0, 2], [3, 5], [1, 6]].

  • For the query [0, 2], the sum is 3 + 1 + 4 = 8.
  • For the query [3, 5], the sum is 1 + 5 + 9 = 15.
  • For the query [1, 6], the sum is 1 + 4 + 1 + 5 + 9 + 2 = 22.

A common approach to quickly answer these queries is to use the prefix sums technique. First, compute the prefix sum array, where each element at index i is the sum of all elements from 0 to i in nums. Then use this array to answer each query in constant time.

Note: Although today (February 15, 2025) might not be a typical holiday, it's a great day to celebrate problem-solving skills by mastering efficient techniques such as prefix sums!

Task

Implement a function that takes in an integer array nums and a list of queries, and returns a list of sums corresponding to each query.

Starter Code

Below is some language-agnostic starter code to help you begin your solution.

function prefixRangeSum(nums, queries) {
    // nums: array of integers
    // queries: list of pairs [L, R] representing the query range (inclusive)
    // returns: list of sums for each query
}