Range Sum Query 2D - Immutable — LeetCode 304 Python Solution

MediumDesignArrayMatrixPrefix Sum
Problem
#304
Pattern
Prefix Sum
Reading time
4 min

The problem

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.

Example

Input
["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
Output
[null, 8, 11, 12]
Explanation
NumMatrix numMatrix = new NumMatrix([[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]]);

Python solution

Python
class NumMatrix:
    def __init__(self, matrix: List[List[int]]):
        m, n = len(matrix), len(matrix[0])
        self.s = [[0] * (n + 1) for _ in range(m + 1)]
        for i, row in enumerate(matrix):
            for j, v in enumerate(row):
                self.s[i + 1][j + 1] = (
                    self.s[i][j + 1] + self.s[i + 1][j] - self.s[i][j] + v
                )

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return (
            self.s[row2 + 1][col2 + 1]
            - self.s[row2 + 1][col1]
            - self.s[row1][col2 + 1]
            + self.s[row1][col1]
        )


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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(m \times n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 304. Range Sum Query 2D - Immutable is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 304. Range Sum Query 2D - Immutable?
LeetCode 304. Range Sum Query 2D - Immutable is rated Medium on LeetCode.
What is the time complexity of LeetCode 304. Range Sum Query 2D - Immutable?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 304. Range Sum Query 2D - Immutable?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 304. Range Sum Query 2D - Immutable cover?
LeetCode 304. Range Sum Query 2D - Immutable is tagged Design, Array, Matrix and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview