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 nums once, in its constructor, and then answers questions about it. Each question gives two positions, left and right, and asks for the sum of the numbers from position left to position right, both included. The method sumRange(left, right) answers one question. The array never changes after the constructor, which is what "immutable" in the title means, and the class may be asked many questions.

Example
Input: nums = [-2, 0, 3, -5, 2, -1]
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
Solution

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] and the question sumRange(2, 5). Adding the numbers at positions 2 to 5 gives 3 - 5 + 2 - 1 = -1. That is fine for one question. But the class is asked again and again, and the questions overlap: sumRange(0, 5) adds positions 2 to 5 all over again. So can the class do some work once, in the constructor, so that every question after that is quick?

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. Look at the picture below.

The array nums = -2, 0, 3, -5, 2, -1 with the running totals prefix = 0, -2, -2, 1, -4, -2, -3 placed between its numbers. Positions 2 to 5 of nums are highlighted. prefix[6] = -3 and prefix[2] = -2 are highlighted, and sumRange(2, 5) = -3 - (-2) = -1.

Each prefix box hangs from a dashed line at the left edge of a number in nums, and the last one from the right end of the array. So prefix[i] is the sum of all the numbers left of its line. On the far right, prefix[6] is -3, the sum of nums[0..5], short for nums[0] to nums[5]. prefix[2] is -2, the sum of the two numbers before position 2. The orange numbers, positions 2 to 5, are exactly what prefix[6] counts and prefix[2] does not.

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) need? prefix[right + 1] is the sum of nums[0] to nums[right], everything up to the end of the range. It also counts the numbers before position left, which are not part of the range. Those add up to prefix[left], so the answer is prefix[right + 1] - prefix[left].

The extra 0 at the front

Why does prefix have one more slot than nums? Its first slot, prefix[0], holds 0, the sum of no numbers at all. A range that starts at position 0 has nothing before it, and prefix[0] says exactly that. So sumRange(0, 2) is prefix[3] - prefix[0], 1 - 0 = 1, with no special case.

Java Solution

The class has three parts, one for each piece of the approach:

  • prefix: the running totals, one slot longer than nums. prefix[i] is the sum of nums[0] to nums[i - 1].
  • The constructor: fills prefix in one pass, starting from prefix[0] = 0.
  • sumRange: answers a question with prefix[right + 1] - prefix[left].

The main method prints prefix for the example array, asks the three example questions, then a range that starts at position 0, a range of one number, and a question on an array of one number.

Java
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:

Output
prefix = [0, -2, -2, 1, -4, -2, -3]
1
-1
-3
-2
-5
7

The first line is the prefix array from the picture: the leading 0, then the running totals -2, -2, 1, -4, -2 and -3. The next three lines answer the example questions with 1, -1 and -3. The fifth line, -2, is sumRange(0, 0), the first number on its own, computed as prefix[1] - prefix[0]. The sixth line, -5, is sumRange(3, 3): a range of one number gives that number back. The last line, 7, comes from an array that holds only the number 7.

The leading 0 is easy to leave out. Without it, prefix has the same length as nums and each slot includes its own number, so the answer becomes prefix[right] - prefix[left - 1]. For sumRange(0, 2) that reads position -1, and Java stops with ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 6. Such a version needs an extra check for left == 0, which the extra slot makes unnecessary.

The original implementation, RangeSumQueryImmutable.java, is on GitHub.

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 sumRange, where n is the length of nums. The constructor adds each number once. sumRange reads two slots of prefix and subtracts, however wide the range is.
  • Space: O(n). prefix has n + 1 slots and is kept for the life of the object.

For the same idea on a grid of numbers, see Range Sum Query 2D - Immutable.