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 - ImmutableInput Array:-203-52-1Multiple Queries: sumRange(0,2), sumRange(2,5), sumRange(0,5)Build Prefix Sum Array OnceThen answer each query in O(1) using subtractionQuery Results:1-1-3Preprocessing: O(n) | Each Query: O(1) | Space: O(n)
Understanding the Visualization
1
Input
Array nums and multiple sumRange queries
2
Process
Build prefix sum array once, then use formula for each query
3
Output
Array of sum results for each query
Key Takeaway
🎯 Key Insight: Precompute prefix sums once to answer any range query in constant time
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