KatInterview

304. Range Sum Query 2D - Immutable

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 core of this problem is to efficiently calculate the sum of elements within a rectangular sub-region of a given 2D matrix. The key constraint is that the sumRegion function must operate in O(1) time. A naive approach of iterating through the specified rectangle for each query would be O(rows * cols), which is too slow given the constraints and the number of calls.

Solution

Range Sum Query 2D - Immutable in Python

class NumMatrix:

    def __init__(self, matrix: List[List[int]]):
        # Handle empty matrix case, although constraints say it won't be empty.
        if not matrix or not matrix[0]:
            return
        
        m, n = len(matrix), len(matrix[0])
        
        # Initialize sums matrix with size (m+1) x (n+1) to handle edge cases gracefully.
        # self.sums[i][j] will store the sum of the rectangle from (0,0) to (i-1, j-1)
        self.sums = [[0] * (n + 1) for _ in range(m + 1)]
        
        # Pre-compute the sums for all rectangles starting from (0,0).
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                # The sum of the rectangle ending at (i-1, j-1) is calculated using
                # the principle of inclusion-exclusion.
                # sums[i][j] = matrix[i-1][j-1] + sum_of_rect_above + sum_of_rect_left - sum_of_overlap
                self.sums[i][j] = matrix[i - 1][j - 1] + self.sums[i - 1][j] + self.sums[i][j - 1] - self.sums[i - 1][j - 1]

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        # The sum of a region is calculated using the pre-computed sums table.
        # It's the sum of the large rectangle ending at (row2, col2)
        # minus the sum of the rectangle above it,
        # minus the sum of the rectangle to the left of it,
        # plus the sum of the top-left rectangle that was subtracted twice.
        # Note the +1 adjustments to map 0-indexed matrix coordinates to 1-indexed sums table.
        return self.sums[row2 + 1][col2 + 1] - self.sums[row1][col2 + 1] - self.sums[row2 + 1][col1] + self.sums[row1][col1]


# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)

Range Sum Query 2D - Immutable in Java

class NumMatrix {
    // sums[i][j] will store the sum of the rectangle from (0,0) to (i-1, j-1)
    private int[][] sums;

    public NumMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        int m = matrix.length;
        int n = matrix[0].length;

        // Initialize sums matrix with size (m+1) x (n+1) to handle edge cases gracefully.
        sums = new int[m + 1][n + 1];

        // Pre-compute the sums for all rectangles starting from (0,0).
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                // The sum of the rectangle ending at (i-1, j-1) is calculated using
                // the principle of inclusion-exclusion.
                // sums[i][j] = matrix[i-1][j-1] + sum_of_rect_above + sum_of_rect_left - sum_of_overlap
                sums[i][j] = matrix[i - 1][j - 1] + sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1];
            }
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        // The sum of a region is calculated using the pre-computed sums table.
        // It's the sum of the large rectangle ending at (row2, col2)
        // minus the sum of the rectangle above it,
        // minus the sum of the rectangle to the left of it,
        // plus the sum of the top-left rectangle that was subtracted twice.
        // Note the +1 adjustments to map 0-indexed matrix coordinates to 1-indexed sums table.
        return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * int param_1 = obj.sumRegion(row1,col1,row2,col2);
 */

Range Sum Query 2D - Immutable in C++

class NumMatrix {
private:
    // sums[i][j] will store the sum of the rectangle from (0,0) to (i-1, j-1)
    vector<vector<int>> sums;

public:
    NumMatrix(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) {
            return;
        }
        int m = matrix.size();
        int n = matrix[0].size();
        
        // Initialize sums matrix with size (m+1) x (n+1) to handle edge cases gracefully.
        sums.resize(m + 1, vector<int>(n + 1, 0));
        
        // Pre-compute the sums for all rectangles starting from (0,0).
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                // The sum of the rectangle ending at (i-1, j-1) is calculated using
                // the principle of inclusion-exclusion.
                // sums[i][j] = matrix[i-1][j-1] + sum_of_rect_above + sum_of_rect_left - sum_of_overlap
                sums[i][j] = matrix[i - 1][j - 1] + sums[i - 1][j] + sums[i][j - 1] - sums[i - 1][j - 1];
            }
        }
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        // The sum of a region is calculated using the pre-computed sums table.
        // It's the sum of the large rectangle ending at (row2, col2)
        // minus the sum of the rectangle above it,
        // minus the sum of the rectangle to the left of it,
        // plus the sum of the top-left rectangle that was subtracted twice.
        // Note the +1 adjustments to map 0-indexed matrix coordinates to 1-indexed sums table.
        return sums[row2 + 1][col2 + 1] - sums[row1][col2 + 1] - sums[row2 + 1][col1] + sums[row1][col1];
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */

Range Sum Query 2D - Immutable in TypeScript

class NumMatrix {
    // sums[i][j] will store the sum of the rectangle from (0,0) to (i-1, j-1)
    private sums: number[][];

    constructor(matrix: number[][]) {
        if (matrix.length === 0 || matrix[0].length === 0) {
            this.sums = [];
            return;
        }
        const m = matrix.length;
        const n = matrix[0].length;
        
        // Initialize sums matrix with size (m+1) x (n+1) to handle edge cases gracefully.
        this.sums = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));

        // Pre-compute the sums for all rectangles starting from (0,0).
        for (let i = 1; i <= m; i++) {
            for (let j = 1; j <= n; j++) {
                // The sum of the rectangle ending at (i-1, j-1) is calculated using
                // the principle of inclusion-exclusion.
                // sums[i][j] = matrix[i-1][j-1] + sum_of_rect_above + sum_of_rect_left - sum_of_overlap
                this.sums[i][j] = matrix[i - 1][j - 1] + this.sums[i - 1][j] + this.sums[i][j - 1] - this.sums[i - 1][j - 1];
            }
        }
    }

    sumRegion(row1: number, col1: number, row2: number, col2: number): number {
        // The sum of a region is calculated using the pre-computed sums table.
        // It's the sum of the large rectangle ending at (row2, col2)
        // minus the sum of the rectangle above it,
        // minus the sum of the rectangle to the left of it,
        // plus the sum of the top-left rectangle that was subtracted twice.
        // Note the +1 adjustments to map 0-indexed matrix coordinates to 1-indexed sums table.
        return this.sums[row2 + 1][col2 + 1] - this.sums[row1][col2 + 1] - this.sums[row2 + 1][col1] + this.sums[row1][col1];
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * var obj = new NumMatrix(matrix)
 * var param_1 = obj.sumRegion(row1,col1,row2,col2)
 */

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.