Range Sum Query - Immutable
Answer many sum questions about a fixed array quickly, by storing running totals once.
Write a class that gets an array of integers numsleftrightleftrightsumRange(left, right)
Example
sumRange(0, 2) returns 1, because -2 + 0 + 3 = 1
sumRange(2, 5) returns -1, because 3 + (-5) + 2 + (-1) = -1
sumRange(0, 5) returns -3, the sum of the whole array
The Idea
Many cars have a trip counter that keeps adding up the kilometres driven since it was last reset. To find how far you drove between two towns, you do not add up every stretch of road again. You read the counter in each town and subtract the first reading from the second.
This problem asks the same of an array. Take nums = [-2, 0, 3, -5, 2, -1]sumRange(2, 5)sumRange(0, 5)
It can, if it keeps a running total, like the trip counter. Walk along the array and write down the total so far before each number. It is 0 before anything, -2 after the first number, still -2 after the 0, then 1 after the 3, and so on, ending with -3 after all six. Each of these totals is the sum of a beginning part of the array, called a prefix, so they are called prefix sums. Keep them in an array called prefix
Each prefixnumsprefix[i]prefix[6]nums[0..5]nums[0]nums[5]prefix[2]prefix[6]prefix[2]
So the sum of a range is the difference of two running totals: -3 - (-2) = -1, the same answer as before, from a single subtraction. That works for any range, however long, just like the two readings of the trip counter.
Solution Approach
Turning that idea into code means settling three things: when to build the running totals, which two totals a range needs, and what goes in the first slot of prefix
Building the totals once
Why not just add up the range on every call? It gives the right answer, but each call reads every number in the range. With 10,000 numbers and 10,000 questions about the whole array, that is about 100 million additions. The array never changes, so its running totals never change either. The constructor builds them once, in one pass: each total is the one before it plus the next number, prefix[i + 1] = prefix[i] + nums[i]
Turning a range into two totals
Which two totals does sumRange(left, right)prefix[right + 1]nums[0]nums[right]leftprefix[left]prefix[right + 1] - prefix[left]
The extra 0 at the front
Why does prefixnumsprefix[0]prefix[0]sumRange(0, 2)prefix[3] - prefix[0]
Java Solution
The class has three parts, one for each piece of the approach:
: the running totals, one slot longer thanprefix .nums is the sum ofprefix[i] tonums[0] .nums[i - 1]- The constructor: fills
in one pass, starting fromprefix .prefix[0] = 0 : answers a question withsumRange .prefix[right + 1] - prefix[left]
The mainprefix
import java.util.Arrays;
public class RangeSumQueryImmutable {
private final int[] prefix; // prefix[i] = nums[0] + ... + nums[i-1]
public RangeSumQueryImmutable(int[] nums) {
prefix = new int[nums.length + 1]; // prefix[0] stays 0, the sum of nothing
for (int i = 0; i < nums.length; i++) {
prefix[i + 1] = prefix[i] + nums[i];
}
}
public int sumRange(int left, int right) {
return prefix[right + 1] - prefix[left]; // everything up to right, minus before left
}
public static void main(String[] args) {
RangeSumQueryImmutable q = new RangeSumQueryImmutable(new int[] {-2, 0, 3, -5, 2, -1});
System.out.println("prefix = " + Arrays.toString(q.prefix));
System.out.println(q.sumRange(0, 2));
System.out.println(q.sumRange(2, 5));
System.out.println(q.sumRange(0, 5));
System.out.println(q.sumRange(0, 0)); // a range that starts at position 0
System.out.println(q.sumRange(3, 3)); // a range of one number
RangeSumQueryImmutable one = new RangeSumQueryImmutable(new int[] {7});
System.out.println(one.sumRange(0, 0)); // an array of one number
}
}
Running it prints:
prefix = [0, -2, -2, 1, -4, -2, -3]
1
-1
-3
-2
-5
7
The first line is the prefixsumRange(0, 0)prefix[1] - prefix[0]sumRange(3, 3)
The leading 0 is easy to leave out. Without it, prefixnumsprefix[right] - prefix[left - 1]sumRange(0, 2)ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6left == 0
The original implementation,
Complexity
The work is one pass over the array in the constructor, and after that a fixed amount for each question.
- Time: O(n) for the constructor and O(1) for each
, where n is the length ofsumRange . The constructor adds each number once.nums reads two slots ofsumRange and subtracts, however wide the range is.prefix - Space: O(n).
has n + 1 slots and is kept for the life of the object.prefix
For the same idea on a grid of numbers, see