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, RangeSumQuery2DImmutablesumRegion(row1, col1, row2, col2)(row1, col1)(row2, col2)
The matrix never changes after the constructor, which is what "immutable" means. sumRegion
Example
sumRegion(2, 1, 4, 3) returns 8
sumRegion(1, 1, 2, 2) returns 11
sumRegion(1, 2, 2, 4) returns 12
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)
A single row of numbers has a known trick, used in
In a grid, the matching total is the sum of a block that starts at the top-left cell, (0, 0)(0, 0)(r, c)(r, c)
On the left is the query. Next to it, the prefix to (2, 4)(2, 1)(0, 4)
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)
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, prefixprefix
Everything else then moves down and right by one: prefix[i][j](i - 1, j - 1)(2, 4)prefix[3][5]prefix
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]matrix[i - 1][j - 1]prefix[i - 1][j]prefix[i][j - 1]
The block up and to the left, prefix[i - 1][j - 1](1, 1)
Answering a query
Which four cells does a query read? With the shift by one, the prefix to (row2, col2)prefix[row2 + 1][col2 + 1]prefix[row1][col2 + 1]prefix[row2 + 1][col1]prefix[row1][col1]
prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1] - prefix[row2 + 1][col1] + prefix[row1][col1]
For sumRegion(1, 2, 2, 4)prefix[3][5]prefix[1][5]prefix[3][2]prefix[1][2]row1prefix[row1][...]
Java Solution
The class has three parts, one for each piece of the approach:
: the table of prefixes, with the extra row and column of zeros. It is built once and read by every query.prefix- The constructor: fills
row by row, as the cell itself plus the block above plus the block to the left, minus their overlap.prefix : reads four cells ofsumRegion and combines them with two subtractions and one addition.prefix
The main
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:
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)prefix[5][5]
The fifth line, 7, is the single cell (3, 4)
The original implementation,
Complexity
The work is split between building prefix
- 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
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).prefix - Space: O(m × n). The object keeps
, with (m + 1) × (n + 1) cells. A query needs no extra space.prefix