Menu
CoddyTech

Range Sum Query

EasyPrefix sumpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums that never changes and a list of queries. Each query is a pair [left, right] of 0-based indexes, and it asks for nums[left] + nums[left+1] + ... + nums[right], both ends included. Return the answers in the same order as the queries.

Function

sumRange(nums: integer-array, queries: integer-2d-array) → integer-array
numsinteger-array
the array of integers, the same for every query
queriesinteger-2d-array
the ranges to add up, each a pair [left, right] with left ≤ right
Returnsinteger-array
the sum of each range, one per query, in query order

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • 1 ≤ queries.length ≤ 1500
  • 0 ≤ left ≤ right < nums.length for every query [left, right]

Examples

Input
nums = [3, -2, 5, 1, -4, 6]queries = [[0, 2], [1, 4], [3, 3]]
Output
[6, 0, 1]
Explanation
Indexes 0 to 2 hold 3 + (-2) + 5 = 6. Indexes 1 to 4 hold -2 + 5 + 1 + (-4) = 0. The range [3, 3] is the single value 1.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Now the numbers form a grid, and each query asks for the sum of a rectangle given by two corners. How would you extend prefix sums to answer each query with a constant number of operations?

Reset code
def sumRange(nums, queries):
    # Write code here
Test cases

Case 1

Case 2

Input

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

Expected

[6, 0, 1]