Practice › Arrays
2D Range Sum Queries
Medium · Arrays · Asked at Amazon, Google, Microsoft, Meta
Given an R × C matrix, answer q queries. Each query r1 c1 r2 c2 (1-based, r1 ≤ r2, c1 ≤ c2) asks for the sum of the sub-matrix with top-left corner (r1, c1) and bottom-right corner (r2, c2).
Input
First line: R C. Next R lines: C integers each. Then a line with q, and q lines r1 c1 r2 c2.
Output
q lines — the sum for each query.
Constraints
- 1 ≤ R, C ≤ 500
- 1 ≤ q ≤ 10^5
- −10^9 ≤ a[i][j] ≤ 10^9
Build P[i][j] = sum of the rectangle (1,1)…(i,j): P[i][j] = a + P[i−1][j] + P[i][j−1] − P[i−1][j−1]. Then a query is P[r2][c2] − P[r1−1][c2] − P[r2][c1−1] + P[r1−1][c1−1]. Sums can reach 2.5 × 10^14, so use 64-bit integers.
Example 1
Input
3 3 1 2 3 4 5 6 7 8 9 3 1 1 2 2 2 2 3 3 1 1 3 3
Output
12 28 45
Hints
- Summing each query cell by cell is up to 2.5 × 10^5 × 10^5 operations.
- Pre-compute P[i][j] = sum of the rectangle from (1, 1) to (i, j).
- Any rectangle is then four lookups, using inclusion–exclusion.
Approach
Build the prefix matrix with P[i][j] = a[i][j] + P[i−1][j] + P[i][j−1] − P[i−1][j−1] (the overlap was added twice). For a query, take the big rectangle P[r2][c2], remove the strip above (P[r1−1][c2]) and the strip to the left (P[r2][c1−1]), and add back the corner removed twice (P[r1−1][c1−1]). Sums can reach 2.5 × 10^14, so use 64-bit integers.
Complexity: O(R · C + q) time · O(R · C) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int R, C;
cin >> R >> C;
vector<vector<long long>> P(R + 1, vector<long long>(C + 1, 0));
for (int i = 1; i <= R; i++)
for (int j = 1; j <= C; j++) {
long long x;
cin >> x;
P[i][j] = x + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
}
int q;
cin >> q;
while (q--) {
int r1, c1, r2, c2;
cin >> r1 >> c1 >> r2 >> c2;
cout << P[r2][c2] - P[r1 - 1][c2] - P[r2][c1 - 1] + P[r1 - 1][c1 - 1] << "\n";
}
return 0;
}Python solution
import sys
data = sys.stdin.buffer.read().split()
R, C = int(data[0]), int(data[1])
P = [[0] * (C + 1) for _ in range(R + 1)]
p = 2
for i in range(1, R + 1):
row, above = P[i], P[i - 1]
run = 0
for j in range(1, C + 1):
run += int(data[p])
p += 1
row[j] = above[j] + run
q = int(data[p])
p += 1
out = []
for _ in range(q):
r1, c1, r2, c2 = int(data[p]), int(data[p + 1]), int(data[p + 2]), int(data[p + 3])
p += 4
out.append(P[r2][c2] - P[r1 - 1][c2] - P[r2][c1 - 1] + P[r1 - 1][c1 - 1])
print("\n".join(map(str, out)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int R = (int) in.nval;
in.nextToken();
int C = (int) in.nval;
long[][] P = new long[R + 1][C + 1];
for (int i = 1; i <= R; i++)
for (int j = 1; j <= C; j++) {
in.nextToken();
P[i][j] = (long) in.nval + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
}
in.nextToken();
int q = (int) in.nval;
StringBuilder sb = new StringBuilder();
for (int k = 0; k < q; k++) {
int[] v = new int[4];
for (int t = 0; t < 4; t++) {
in.nextToken();
v[t] = (int) in.nval;
}
int r1 = v[0], c1 = v[1], r2 = v[2], c2 = v[3];
sb.append(P[r2][c2] - P[r1 - 1][c2] - P[r2][c1 - 1] + P[r1 - 1][c1 - 1]).append('\n');
}
System.out.print(sb);
}
}