#304
Medium Algorithms Range sum query 2d immutable
Array Design Matrix Prefix Sum
57.9% acceptance
Jan 12, 2026
5374
371
Given a 2D matrix matrix, handle multiple queries of the following type:
Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Implement the NumMatrix class:
NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
You must design an algorithm where sumRegion works on O(1) time complexity.
Solution
Rust
Time O(n * m)
Space O(n * m)
* impl NumMatrix {
* fn new(matrix: Vec<Vec<i32>>) -> Self {
* }
* fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 {
* }
* }
*/
impl NumMatrix {
fn new(matrix: Vec<Vec<i32>>) -> Self {
let m = matrix.len();
let n = matrix[0].len();
let mut prefix_sum = vec![vec![0; n + 1]; m + 1];
for i in 1..=m {
for j in 1..=n {
prefix_sum[i][j] = matrix[i-1][j-1] + prefix_sum[i-1][j] +
prefix_sum[i][j-1] - prefix_sum[i-1][j-1];
}
}
NumMatrix { prefix_sum }
}
fn sum_region(&self, row1: i32, col1: i32, row2: i32, col2: i32) -> i32 {
let r1 = row1 as usize;
let c1 = col1 as usize;
let r2 = row2 as usize + 1;
let c2 = col2 as usize + 1;
self.prefix_sum[r2][c2] - self.prefix_sum[r1][c2] -
self.prefix_sum[r2][c1] + self.prefix_sum[r1][c1]
}
}
/*
* Your NumMatrix object will be instantiated and called as such:
* let obj = NumMatrix::new(matrix);
* let ret_1: i32 = obj.sum_region(row1, col1, row2, col2);
*/