Range Sum Query - Immutable - Problem

Given an integer array nums, handle multiple queries of the following type:

Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:

  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive.

Input & Output

Example 1 — Basic Range Queries
$ Input: nums = [-2,0,3,-5,2,-1], operations = [["sumRange",0,2],["sumRange",2,5],["sumRange",0,5]]
Output: [1,-1,-3]
💡 Note: sumRange(0,2) = (-2) + 0 + 3 = 1, sumRange(2,5) = 3 + (-5) + 2 + (-1) = -1, sumRange(0,5) = (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
Example 2 — Single Element Range
$ Input: nums = [1,3,5], operations = [["sumRange",1,1],["sumRange",0,2]]
Output: [3,9]
💡 Note: sumRange(1,1) = nums[1] = 3, sumRange(0,2) = 1 + 3 + 5 = 9
Example 3 — Full Array Range
$ Input: nums = [5,-3,5], operations = [["sumRange",0,0],["sumRange",1,2],["sumRange",0,2]]
Output: [5,2,7]
💡 Note: sumRange(0,0) = 5, sumRange(1,2) = -3 + 5 = 2, sumRange(0,2) = 5 + (-3) + 5 = 7

Constraints

  • 1 ≤ nums.length ≤ 104
  • -105 ≤ nums[i] ≤ 105
  • 0 ≤ left ≤ right < nums.length
  • At most 104 calls to sumRange

Visualization

Tap to expand
Range Sum Query - Immutable INPUT nums array: -2 0 0 1 3 2 -5 3 2 4 -1 5 Queries: sumRange(0, 2) sumRange(2, 5) sumRange(0, 5) ALGORITHM STEPS 1 Build Prefix Sum prefix[i] = sum of nums[0..i-1] prefix: 0 -2 -2 1 -4 -2 -3 2 Query Formula sum(l,r) = prefix[r+1] - prefix[l] 3 Query 1: sumRange(0,2) prefix[3] - prefix[0] = 1 - 0 = 1 4 Query 2: sumRange(2,5) prefix[6] - prefix[2] = -3 - (-2) = -1 5 Query 3: sumRange(0,5) prefix[6] - prefix[0] = -3 - 0 = -3 Init: O(n) | Query: O(1) FINAL RESULT Output Array: 1 -1 -3 sumRange(0,2) = -2+0+3 = 1 sumRange(2,5) = 3-5+2-1 = -1 sumRange(0,5) = -2+0+3-5+2-1 = -3 OK All queries computed in O(1) time each! Key Insight: Prefix sum array allows O(1) range queries. prefix[i] stores sum of all elements before index i. Sum of range [left, right] = prefix[right+1] - prefix[left]. One-time O(n) preprocessing enables unlimited fast queries. TutorialsPoint - Range Sum Query - Immutable | Optimal Solution (Prefix Sum)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
285.0K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen