Range Sum Queries

easy · arrays, prefix sums

Range Sum Queries

You are given an integer slice nums and a list of inclusive range queries queries.

Each query is a pair [l, r] meaning "sum of nums[l] through nums[r]" (0‑based indexing). Return a slice where each element is the sum for its corresponding query.

Function signature

func RangeSumQueries(nums []int, queries [][2]int) []int

In Python, implement range_sum_queries(nums, queries).

Example

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

Constraints

  • 1 <= len(nums) <= 200_000
  • 1 <= len(queries) <= 200_000
  • -1_000 <= nums[i] <= 1_000
  • 0 <= l <= r < len(nums)

Aim for O(n + q) time for n readings and q queries.

Try it before coding

For readings [5, −2, 1], answer the queries [1,1] and [0,1]. Which gap is shared by the two subtractions?

Check your reasoning

Both end at gap 2, where the running total is 3. Subtract the total 5 at gap 1 to get −2, or the total 0 at gap 0 to get 3.

Run tests to see results
No issues detected
    Join Discord