Back to ArraysRange Sum Query — Immutable
Easy

Range Sum Query — Immutable

EasyRecommendedPrefix Sum

Given a fixed array and a list of [left, right] range queries, return the sum of each range. DeepLogic's adaptation asks for every query's answer at once, in a single call, rather than modeling repeated method calls on a stored object.

Examples

Example 1

Input:
nums = [-2,0,3,-5,2,-1], queries = [[0,2],[2,5],[0,5]]
Output:
[1,-1,-3]

Explanation: Each query's sum is read off the same precomputed prefix array in O(1): indices 0-2 sum to 1, 2-5 sum to -1, and the whole array sums to -3.

Example 2

Input:
nums = [1,2,3,4,5], queries = [[1,3]]
Output:
[9]

Explanation: A single query still uses the same prefix array: indices 1-3 are 2 + 3 + 4 = 9.

Example 3

Input:
nums = [4,-2,3,-1,6], queries = [[0,4],[1,3],[2,2]]
Output:
[10,0,3]

Explanation: Query [2,2] is a single-element range (just nums[2] = 3), and [1,3] shows the sum can be 0 even with nonzero elements on both signs.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^5 <= nums[i] <= 10^5
  • 1 <= queries.length <= 10^4
  • 0 <= left <= right <= nums.length - 1

Follow-up

How would the approach change if nums could be updated between queries — what would break about the O(1)-per-query guarantee?

Loading editor…

Code execution is coming soon.