Range Sum Query 2D Immutable

Answer many sum queries over blocks of a fixed matrix, each in constant time, from a table built once.

You are given a matrix of integers with at least one row and one column. Write a class, RangeSumQuery2DImmutable, whose constructor takes the matrix once. Its method sumRegion(row1, col1, row2, col2) returns the sum of the block of cells whose top-left cell is (row1, col1) and whose bottom-right cell is (row2, col2). Rows and columns count from 0.

The matrix never changes after the constructor, which is what "immutable" means. sumRegion is called many times, and each call should take the same short time however big the block is.

Example
Input: matrix = [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]
sumRegion(2, 1, 4, 3) returns 8
sumRegion(1, 1, 2, 2) returns 11
sumRegion(1, 2, 2, 4) returns 12
Solution

The Idea

Picture a spreadsheet full of numbers. Someone selects a block of cells and asks for its total, then another block, then another, thousands of times, while the numbers stay the same. Adding up every selected cell works, but a big block means a long addition for every question.

Look at the third query of the example, sumRegion(1, 2, 2, 4). Its block covers rows 1 and 2 and columns 2 to 4: the numbers 3, 2 and 1 in row 1, and 0, 1 and 5 in row 2. Their total is 12. Can we get 12 without visiting those six cells?

A single row of numbers has a known trick, used in Range Sum Query - Immutable. Keep running totals: if the first 7 numbers add up to 20 and the first 3 to 5, then numbers 4 to 7 add up to 20 - 5 = 15. A total of everything up to some point is called a prefix sum.

In a grid, the matching total is the sum of a block that starts at the top-left cell, (0, 0). We will call the sum of the block from (0, 0) down to a cell (r, c) the prefix to (r, c). Look at the picture below.

The query, rows 1 to 2 and columns 2 to 4, equals the prefix to (2, 4), 36, minus the prefix to (2, 1), 17, minus the prefix to (0, 4), 10, plus the prefix to (0, 1), 3: 12.

On the left is the query. Next to it, the prefix to (2, 4) contains the query, and its total is 36. That is too much, because it also holds columns 0 and 1, and row 0. Taking away the prefix to (2, 1), which is 17, removes columns 0 and 1. Taking away the prefix to (0, 4), which is 10, removes row 0.

But the cells 3 and 0 in the top-left corner are in both of those blocks, so they were taken away twice. Adding back the prefix to (0, 1), which is 3, puts them back once: 36 - 17 - 10 + 3 = 12.

So the sum of any block is four prefixes, combined with two subtractions and one addition. If the prefix to every cell is worked out once, at the start, each query is four lookups, however big its block. Adding two overlapping parts and taking the overlap away once is known as inclusion-exclusion.

Solution Approach

Turning that idea into code means settling three things: where the prefixes are stored, how to compute all of them quickly, and how a query reads four of them.

Storing the prefixes

Is a table really worth it? Adding up each block directly costs one addition per cell. A block can be the whole matrix, so on a 200 by 200 matrix, 10,000 queries could take 400 million additions. With a table, the same queries take 40,000 lookups.

The table is a 2D array, prefix. Where would a query that starts in row 0 find the prefix of the rows above it? Those rows do not exist, so their sum is 0. To keep that case like any other, prefix gets one extra row of zeros at the top and one extra column of zeros on the left.

Everything else then moves down and right by one: prefix[i][j] holds the prefix to (i - 1, j - 1). For example, the prefix to (2, 4), 36, is stored in prefix[3][5]. A matrix with m rows and n columns gets a prefix array of m + 1 rows and n + 1 columns.

Filling the table

Adding up a whole block for every cell would be slow again. Can a cell reuse the cells already filled? The same overlap trick works the other way round. The block for prefix[i][j] is the matrix cell matrix[i - 1][j - 1], plus the block above it, prefix[i - 1][j], plus the block to its left, prefix[i][j - 1].

The block up and to the left, prefix[i - 1][j - 1], is inside both of those, so it is taken away once. Take the matrix cell 6 at (1, 1). The block above it holds 3 and 0, the block to its left holds 3 and 5, and the 3 they share is the overlap: 6 + 3 + 8 - 3 = 14, the sum of 3, 0, 5 and 6. Filling the table row by row, left to right, means the three cells each new cell needs are always ready.

Answering a query

Which four cells does a query read? With the shift by one, the prefix to (row2, col2) is prefix[row2 + 1][col2 + 1]. The rows above the query form prefix[row1][col2 + 1], and the columns to its left form prefix[row2 + 1][col1]. The corner taken away twice is prefix[row1][col1]. So the answer is:

prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1] - prefix[row2 + 1][col1] + prefix[row1][col1]

For sumRegion(1, 2, 2, 4) that reads prefix[3][5], prefix[1][5], prefix[3][2] and prefix[1][2]: the 36, 10, 17 and 3 from the picture. When row1 is 0, prefix[row1][...] lands in the extra row of zeros, so nothing is taken away, which is exactly right.

Java Solution

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

  • prefix: the table of prefixes, with the extra row and column of zeros. It is built once and read by every query.
  • The constructor: fills prefix row by row, as the cell itself plus the block above plus the block to the left, minus their overlap.
  • sumRegion: reads four cells of prefix and combines them with two subtractions and one addition.

The main method runs the three queries of the example, then the whole matrix, a single cell, the top-left cell, a matrix of one cell, and a small matrix with negative numbers.

Java
public class RangeSumQuery2DImmutable {

    private final int[][] prefix;             // prefix[i][j] = sum of matrix[0..i-1][0..j-1]

    public RangeSumQuery2DImmutable(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        prefix = new int[m + 1][n + 1];       // extra top row and left column of zeros
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                prefix[i][j] = matrix[i - 1][j - 1]
                        + prefix[i - 1][j]        // block above
                        + prefix[i][j - 1]        // block to the left
                        - prefix[i - 1][j - 1];   // counted twice, so take it away once
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        return prefix[row2 + 1][col2 + 1]
                - prefix[row1][col2 + 1]      // rows above the region
                - prefix[row2 + 1][col1]      // columns left of the region
                + prefix[row1][col1];         // removed twice, so add it back
    }

    public static void main(String[] args) {
        int[][] matrix = {
            {3, 0, 1, 4, 2},
            {5, 6, 3, 2, 1},
            {1, 2, 0, 1, 5},
            {4, 1, 0, 1, 7},
            {1, 0, 3, 0, 5}
        };
        RangeSumQuery2DImmutable q = new RangeSumQuery2DImmutable(matrix);
        System.out.println(q.sumRegion(2, 1, 4, 3));
        System.out.println(q.sumRegion(1, 1, 2, 2));
        System.out.println(q.sumRegion(1, 2, 2, 4));
        System.out.println(q.sumRegion(0, 0, 4, 4));   // the whole matrix
        System.out.println(q.sumRegion(3, 4, 3, 4));   // one cell
        System.out.println(q.sumRegion(0, 0, 0, 0));   // the top-left cell

        RangeSumQuery2DImmutable one = new RangeSumQuery2DImmutable(new int[][] {{7}});
        System.out.println(one.sumRegion(0, 0, 0, 0));

        RangeSumQuery2DImmutable mixed = new RangeSumQuery2DImmutable(new int[][] {
            {-2, 4},
            {3, -5}
        });
        System.out.println(mixed.sumRegion(0, 0, 1, 1));
        System.out.println(mixed.sumRegion(0, 1, 1, 1));
    }
}

Running it prints:

Output
8
11
12
58
7
3
7
0
-1

The first three lines are the example: 8, 11 and 12. The fourth line, 58, is the whole matrix. Its block starts at (0, 0), so three of the four lookups land in the extra row and column of zeros, and the answer is prefix[5][5] alone. The sixth line, 3, is the top-left cell, and its query reads the zeros in the same way.

The fifth line, 7, is the single cell (3, 4) treated as a block of its own. The seventh line, also 7, comes from a matrix with only one cell. The last two lines use the matrix with negative numbers: the whole of it is -2 + 4 + 3 - 5 = 0, and its right column alone is 4 - 5 = -1. Negative values need no special care, because the formula only adds and subtracts.

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

Complexity

The work is split between building prefix once, in the constructor, and the four lookups of each query.

  • Time: O(m × n) for the constructor, O(1) per query, where m and n are the numbers of rows and columns. The two loops fill each cell of prefix once, with three additions or subtractions. A query reads four cells whatever the size of its block, so it takes constant time, written O(1).
  • Space: O(m × n). The object keeps prefix, with (m + 1) × (n + 1) cells. A query needs no extra space.