Range Sum Query - Immutable
Range Sum Query - Immutable is a easy arrays & hashing problem solved with the prefix sum strategy pattern.
The best approach, optimal (prefix sums), runs in O(n) build, O(1) per query time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force up.
Problem
Design a class that takes an integer array once and then answers many queries sumRange(left, right): the sum of the elements between indices left and right, inclusive. The array never changes.
Examples
Example 1
- Input
NumArray([3, -1, 4, 2]); sumRange(0, 2); sumRange(1, 3)- Output
6, 5- Why
- 3 + -1 + 4 = 6 and -1 + 4 + 2 = 5.
Constraints
1 <= nums.length <= 10^4- At most
10^4calls to sumRange. - The array never changes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (1 examples, or your own). Submit also runs 7 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force | O(n) per query | O(1) |
| Optimal (prefix sums) | O(n) build, O(1) per query | O(n) |
1Brute force
O(n) per queryO(1)Store the array and loop from left to right on every query.
- sumRange adds nums[left..right].
class NumArray {
private final int[] nums;
public NumArray(int[] nums) { this.nums = nums; }
public int sumRange(int left, int right) {
int sum = 0;
for (int i = left; i <= right; i++) sum += nums[i];
return sum;
}
}class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
def sumRange(self, left: int, right: int) -> int:
total = 0
for i in range(left, right + 1):
total += self.nums[i]
return totalclass NumArray {
private:
vector<int> nums;
public:
NumArray(const vector<int>& nums) : nums(nums) {}
int sumRange(int left, int right) {
int sum = 0;
for (int i = left; i <= right; i++) sum += nums[i];
return sum;
}
};class NumArray {
constructor(nums) { this.nums = nums; }
sumRange(left, right) {
let sum = 0;
for (let i = left; i <= right; i++) sum += this.nums[i];
return sum;
}
}2Optimal (prefix sums)
O(n) build, O(1) per queryO(n)Build pre where pre[i] is the sum of the first i elements, with pre[0] = 0. Then the sum of left..right is pre[right + 1] - pre[left].
- pre[i + 1] = pre[i] + nums[i].
- sumRange returns pre[right + 1] - pre[left].
class NumArray {
private final int[] pre;
public NumArray(int[] nums) {
pre = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) pre[i + 1] = pre[i] + nums[i];
}
public int sumRange(int left, int right) {
return pre[right + 1] - pre[left];
}
}class NumArray:
def __init__(self, nums: List[int]):
self.pre = [0] * (len(nums) + 1)
for i in range(len(nums)):
self.pre[i + 1] = self.pre[i] + nums[i]
def sumRange(self, left: int, right: int) -> int:
return self.pre[right + 1] - self.pre[left]class NumArray {
private:
vector<int> pre;
public:
NumArray(const vector<int>& nums) {
pre.assign(nums.size() + 1, 0);
for (int i = 0; i < (int) nums.size(); i++) pre[i + 1] = pre[i] + nums[i];
}
int sumRange(int left, int right) {
return pre[right + 1] - pre[left];
}
};class NumArray {
constructor(nums) {
this.pre = new Array(nums.length + 1).fill(0);
for (let i = 0; i < nums.length; i++) this.pre[i + 1] = this.pre[i] + nums[i];
}
sumRange(left, right) {
return this.pre[right + 1] - this.pre[left];
}
}Edge cases to test
- left == right
- left == 0 (why the prefix array has an extra leading 0)
Hints
Hint 1
If you store prefix sums once, any range sum is a single subtraction.
FAQ
What is the best time complexity for Range Sum Query - Immutable?
Optimal (prefix sums) runs in O(n) build, O(1) per query time and O(n) extra space.
Which pattern does Range Sum Query - Immutable use?
It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Continuous Subarray Sum.
Is there a brute force solution for Range Sum Query - Immutable?
Yes. Brute force takes O(n) per query time and O(1) space. Store the array and loop from left to right on every query.
Which edge cases should I test for Range Sum Query - Immutable?
left == right; left == 0 (why the prefix array has an extra leading 0).