Skip to content

Practice Range Sum Query - Immutable

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#303
LeetCode Problem

Range Sum Query - Immutable

Problem Statement

NumArray(nums) stores a fixed integer array. sumRange(left, right) returns the sum from left through right, including both endpoints. The array does not change between calls. Practice approach: Precompute prefix[0] = 0 and prefix[i + 1] = prefix[i] + nums[i]. A query is prefix[right + 1] - prefix[left]. Preprocessing and storage are O(n), and each query is O(1). The extra leading zero avoids special-casing left = 0. Test negative totals, one-element ranges, and the entire array.

Source: Range Sum Query - Immutable on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["NumArray","sumRange","sumRange","sumRange"]
[[[4,-2,7]],[0,1],[1,2],[2,2]]
Output
[null,2,5,7]
Explanation

The inclusive sums are 4 - 2 = 2, -2 + 7 = 5, and the single value 7.

Constraints

1 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
0 <= left <= right < nums.length
At most 10^4 calls to sumRange.

Related LeetCode Problems

Practice more problems similar to Range Sum Query - Immutable.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.