Answer a Range Sum Query on an Array
Solve this Problemnums, answer queries of the form: what is the sum of the elements between index left and index right, inclusive?
Summing the range directly answers one query correctly, but it re-walks the same ground every time. In a system where the array stays fixed and the same range gets queried over and over, that's wasted work — a prefix sumPrefix SumA precomputed running total, where prefix[i] holds the sum of every element before index i. Once built, the sum of any range can be found with a single subtraction instead of re-adding every element in that range. array, built once, turns every future range query into a single subtraction.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 10⁴ - ◆
-10⁵ ≤ nums[i] ≤ 10⁵ - ◆
0 ≤ left ≤ right < nums.length
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int rangeSum(int[] nums, int left, int right) { |
| 3 | int[] prefix = new int[nums.length + 1]; |
| 4 | for (int i = 0; i < nums.length; i++) { |
| 5 | prefix[i + 1] = prefix[i] + nums[i]; |
| 6 | } |
| 7 | return prefix[right + 1] - prefix[left]; |
| 8 | } |
| 9 | } |
| 10 |
0-2Extend the prefix array: prefix[1] = -2, the sum of nums[0..0].
Approach & Solutions
Brute Force
BruteWalk from left to right, adding each element into a running sum. Correct, but every query re-walks its whole range from scratch — if this array were queried many times, that repeated work adds up fast.
O(n) per queryO(1)1class Solution {
2 public int rangeSum(int[] nums, int left, int right) {
3 int sum = 0;
4 for (int i = left; i <= right; i++) {
5 sum += nums[i];
6 }
7 return sum;
8 }
9}Optimal — Prefix Sum
OptimalBuild a prefix array where prefix[i] holds the sum of every element before index i (so prefix[0] = 0, prefix[1] = nums[0], and so on). Once that's built, the sum of any range [left, right] is just prefix[right + 1] - prefix[left] — one subtraction, no matter how wide the range is. In a real system that answers this query repeatedly against the same array, you'd build the prefix array once and reuse it for every query, turning each one into O(1) instead of O(range). This version rebuilds it on every call to keep the function pure and self-contained, but the underlying trick — and the reason it's fast when reused — is exactly the same.
O(n) to build, O(1) per queryO(n)1class Solution {
2 public int rangeSum(int[] nums, int left, int right) {
3 int[] prefix = new int[nums.length + 1];
4 for (int i = 0; i < nums.length; i++) {
5 prefix[i + 1] = prefix[i] + nums[i];
6 }
7 return prefix[right + 1] - prefix[left];
8 }
9}