You are given a 2D matrix matrix
composed of only integers. Implement the NumMatrix
class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrix matrix
.int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements of matrix from the top-left element (row1, col1)
to the bottom-right element (row2, col2)
inclusive.You must implement the NumMatrix
class such that each call to sumRegion
works in constant time (O(1)).
matrix = [
[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]
]
numMatrix = NumMatrix(matrix)
print(numMatrix.sumRegion(2, 1, 4, 3)) # Output: 8
print(numMatrix.sumRegion(1, 1, 2, 2)) # Output: 11
print(numMatrix.sumRegion(1, 2, 2, 4)) # Output: 12
Before starting, let’s clarify a few points:
row1 <= row2
and col1 <= col2
for each query?Assuming the problem constraints are standard for competitive programming problems, we will develop a plan to address the requirements.
To ensure that each call to sumRegion
works in constant time, we can use a prefix sum approach. The main steps are as follows:
prefix[i][j]
represents the sum of the matrix elements from (0,0)
to (i-1,j-1)
.prefix[i][j]
such that it is the sum of all elements from the top-left corner (0,0)
to (i-1,j-1)
.class NumMatrix:
def __init__(self, matrix):
if not matrix or not matrix[0]:
self.prefix_sum = []
return
rows, cols = len(matrix), len(matrix[0])
self.prefix_sum = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(1, rows + 1):
for c in range(1, cols + 1):
self.prefix_sum[r][c] = matrix[r-1][c-1] + self.prefix_sum[r-1][c] + self.prefix_sum[r][c-1] - self.prefix_sum[r-1][c-1]
def sumRegion(self, row1, col1, row2, col2):
return (self.prefix_sum[row2 + 1][col2 + 1]
- self.prefix_sum[row1][col2 + 1]
- self.prefix_sum[row2 + 1][col1]
+ self.prefix_sum[row1][col1])
# Example Usage
matrix = [
[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]
]
numMatrix = NumMatrix(matrix)
print(numMatrix.sumRegion(2, 1, 4, 3)) # Output: 8
print(numMatrix.sumRegion(1, 1, 2, 2)) # Output: 11
print(numMatrix.sumRegion(1, 2, 2, 4)) # Output: 12
This ensures that our sumRegion
function operates in constant time, meeting the problem’s requirement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?