Skip to content

Practice Range Sum Query 2D - Immutable

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#304
LeetCode Problem

Range Sum Query 2D - Immutable

Problem Statement

NumMatrix(matrix) stores a fixed rectangular matrix. sumRegion(row1, col1, row2, col2) returns the sum of the inclusive rectangle bounded by those corners. Each query must run in O(1) time. Practice approach: Build a two-dimensional prefix table with an extra zero row and column. Add the prefixes above and left, subtract their overlap, and include the current cell. Answer a rectangle with inclusion-exclusion of four prefix entries. Construction and storage are O(mn), then each query is O(1). Test a single cell and a rectangle touching the top or left border.

Source: Range Sum Query 2D - Immutable on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[1,2],[3,4]]],[0,0,1,1],[0,1,1,1],[1,0,1,0]]
Output
[null,10,6,3]
Explanation

The entire matrix sums to 10, its right column to 6, and its bottom-left cell to 3.

Constraints

m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-10^4 <= matrix[i][j] <= 10^4
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
At most 10^4 calls to sumRegion.

Related LeetCode Problems

Practice more problems similar to Range Sum Query 2D - Immutable.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.