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.
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
["NumMatrix","sumRegion","sumRegion","sumRegion"] [[[[1,2],[3,4]]],[0,0,1,1],[0,1,1,1],[1,0,1,0]]
[null,10,6,3]
The entire matrix sums to 10, its right column to 6, and its bottom-left cell to 3.
Constraints
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.