308. Range Sum Query 2D - Mutable
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to perform two types of operations on a 2D matrix: updating the value of a single cell and calculating the sum of a rectangular region. The key challenge is that the matrix is mutable.
Solution
Range Sum Query 2D - Mutable in Python
class NumMatrix:
def __init__(self, matrix: list[list[int]]):
if not matrix or not matrix[0]:
self.m, self.n = 0, 0
return
self.m, self.n = len(matrix), len(matrix[0])
self.matrix = [[0] * self.n for _ in range(self.m)]
# 2D Fenwick Tree (or Binary Indexed Tree)
# Using 1-based indexing, so size is (m+1) x (n+1)
self.bit = [[0] * (self.n + 1) for _ in range(self.m + 1)]
for r in range(self.m):
for c in range(self.n):
self.update(r, c, matrix[r][c])
def update(self, row: int, col: int, val: int) -> None:
delta = val - self.matrix[row][col]
self.matrix[row][col] = val
# Convert to 1-based indexing for BIT
r, c = row + 1, col + 1
while r <= self.m:
c_temp = c
while c_temp <= self.n:
self.bit[r][c_temp] += delta
# Move to parent in the column BIT
c_temp += c_temp & (-c_temp)
# Move to parent in the row BIT
r += r & (-r)
def _query(self, row: int, col: int) -> int:
"""Helper to get sum of rectangle from (0,0) to (row, col)"""
total = 0
# Convert to 1-based indexing for BIT
r, c = row + 1, col + 1
while r > 0:
c_temp = c
while c_temp > 0:
total += self.bit[r][c_temp]
# Move to parent in column BIT
c_temp -= c_temp & (-c_temp)
# Move to parent in row BIT
r -= r & (-r)
return total
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
# Use inclusion-exclusion principle
return (self._query(row2, col2) -
self._query(row1 - 1, col2) -
self._query(row2, col1 - 1) +
self._query(row1 - 1, col1 - 1))
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)
Range Sum Query 2D - Mutable in Java
class NumMatrix {
private int[][] matrix;
private int[][] bit; // 2D Binary Indexed Tree
private int m, n;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return;
this.m = matrix.length;
this.n = matrix[0].length;
this.matrix = new int[m][n];
this.bit = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
update(i, j, matrix[i][j]);
}
}
}
public void update(int row, int col, int val) {
// Calculate the difference to update the BIT
int delta = val - matrix[row][col];
matrix[row][col] = val;
// Update the BIT with the delta
// Using 1-based indexing for BIT
for (int i = row + 1; i <= m; i += i & -i) {
for (int j = col + 1; j <= n; j += j & -j) {
bit[i][j] += delta;
}
}
}
// Helper function to get sum of rectangle from (0,0) to (row, col)
private int query(int row, int col) {
int sum = 0;
// Using 1-based indexing for BIT
for (int i = row + 1; i > 0; i -= i & -i) {
for (int j = col + 1; j > 0; j -= j & -j) {
sum += bit[i][j];
}
}
return sum;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
// Using inclusion-exclusion principle with prefix sums
return query(row2, col2) - query(row1 - 1, col2) - query(row2, col1 - 1) + query(row1 - 1, col1 - 1);
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* obj.update(row,col,val);
* int param_2 = obj.sumRegion(row1,col1,row2,col2);
*/
Range Sum Query 2D - Mutable in C++
class NumMatrix {
private:
int rows, cols;
vector<vector<int>> mat; // Stores the actual matrix values
vector<vector<int>> bit; // The 2D Fenwick Tree (BIT)
// Helper function to update the BIT
void add(int row, int col, int delta) {
// Convert to 1-based index for BIT
for (int i = row + 1; i <= rows; i += i & -i) {
for (int j = col + 1; j <= cols; j += j & -j) {
bit[i][j] += delta;
}
}
}
// Helper function to query prefix sum from (0,0) to (row,col)
int query(int row, int col) {
int sum = 0;
// Convert to 1-based index for BIT
for (int i = row + 1; i > 0; i -= i & -i) {
for (int j = col + 1; j > 0; j -= j & -j) {
sum += bit[i][j];
}
}
return sum;
}
public:
NumMatrix(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) {
rows = 0;
cols = 0;
return;
}
rows = matrix.size();
cols = matrix[0].size();
mat.resize(rows, vector<int>(cols, 0));
bit.resize(rows + 1, vector<int>(cols + 1, 0));
// Initialize the matrix and BIT
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
update(i, j, matrix[i][j]);
}
}
}
void update(int row, int col, int val) {
int delta = val - mat[row][col];
mat[row][col] = val;
add(row, col, delta);
}
int sumRegion(int row1, int col1, int row2, int col2) {
// Using inclusion-exclusion principle
return query(row2, col2) - query(row1 - 1, col2) - query(row2, col1 - 1) + query(row1 - 1, col1 - 1);
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* obj->update(row,col,val);
* int param_2 = obj->sumRegion(row1,col1,row2,col2);
*/
Range Sum Query 2D - Mutable in TypeScript
class NumMatrix {
private matrix: number[][];
private bit: number[][]; // 2D Binary Indexed Tree
private m: number;
private n: number;
constructor(matrix: number[][]) {
if (matrix.length === 0 || matrix[0].length === 0) {
this.m = 0;
this.n = 0;
this.matrix = [];
this.bit = [];
return;
}
this.m = matrix.length;
this.n = matrix[0].length;
this.matrix = Array(this.m).fill(0).map(() => Array(this.n).fill(0));
this.bit = Array(this.m + 1).fill(0).map(() => Array(this.n + 1).fill(0));
for (let i = 0; i < this.m; i++) {
for (let j = 0; j < this.n; j++) {
this.update(i, j, matrix[i][j]);
}
}
}
update(row: number, col: number, val: number): void {
const delta = val - this.matrix[row][col];
this.matrix[row][col] = val;
// Use 1-based indexing for BIT
for (let i = row + 1; i <= this.m; i += i & -i) {
for (let j = col + 1; j <= this.n; j += j & -j) {
this.bit[i][j] += delta;
}
}
}
private query(row: number, col: number): number {
let sum = 0;
// Use 1-based indexing for BIT
for (let i = row + 1; i > 0; i -= i & -i) {
for (let j = col + 1; j > 0; j -= j & -j) {
sum += this.bit[i][j];
}
}
return sum;
}
sumRegion(row1: number, col1: number, row2: number, col2: number): number {
// Use inclusion-exclusion principle
return this.query(row2, col2) -
this.query(row1 - 1, col2) -
this.query(row2, col1 - 1) +
this.query(row1 - 1, col1 - 1);
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = new NumMatrix(matrix)
* obj.update(row,col,val)
* var param_2 = obj.sumRegion(row1,col1,row2,col2)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.