Range Sum Query 2D - Mutable - Problem

You are given a 2D matrix matrix and need to handle two types of operations efficiently:

1. Update Operation: Change the value of any cell in the matrix

2. Range Sum Query: Calculate the sum of all elements within a rectangular region defined by upper-left corner (row1, col1) and lower-right corner (row2, col2)

Implement the NumMatrix class with these methods:

  • NumMatrix(int[][] matrix) - Initialize with the given matrix
  • void update(int row, int col, int val) - Update matrix[row][col] to val
  • int sumRegion(int row1, int col1, int row2, int col2) - Return sum of rectangle region

Note: The rectangle region is inclusive of boundaries.

Input & Output

Example 1 — Basic Operations
$ Input: 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]], operations = [["sumRegion",2,1,4,3],["update",3,2,2],["sumRegion",2,1,4,3]]
Output: [8,10]
💡 Note: First sumRegion(2,1,4,3) returns sum of rectangle from (2,1) to (4,3) = 2+0+1+1+0+1+0+3+0 = 8. After update(3,2,2), matrix[3][2] changes to 2. Second sumRegion returns updated sum = 10.
Example 2 — Single Cell Query
$ Input: matrix = [[1]], operations = [["sumRegion",0,0,0,0],["update",0,0,5],["sumRegion",0,0,0,0]]
Output: [1,5]
💡 Note: Initial single cell has value 1. After updating to 5, the query returns 5.
Example 3 — Multiple Updates
$ Input: matrix = [[1,2],[3,4]], operations = [["update",0,0,10],["update",1,1,20],["sumRegion",0,0,1,1]]
Output: [36]
💡 Note: After updates: matrix becomes [[10,2],[3,20]]. Sum of entire matrix: 10+2+3+20 = 36.

Constraints

  • 1 ≤ matrix.length, matrix[i].length ≤ 200
  • -105 ≤ matrix[i][j] ≤ 105
  • 0 ≤ row < matrix.length
  • 0 ≤ col < matrix[i].length
  • -105 ≤ val ≤ 105
  • 0 ≤ row1 ≤ row2 < matrix.length
  • 0 ≤ col1 ≤ col2 < matrix[i].length
  • At most 104 calls will be made to sumRegion and update

Visualization

Tap to expand
INPUTALGORITHMRESULT301213122Query: Sum(1,1) to (2,2)Operations: sumRegion, update1Build 2D BIT2Update: O(log m × log n)3Query: O(log m × log n)4Inclusion-exclusion principleBIT TreeLog complexitySum = 81 + 3 + 2 + 2Fast UpdatesFast QueriesO(log m × log n)Key Insight:2D Binary Indexed Tree provides balanced O(log m × log n) performance for both updates and range sum queriesTutorialsPoint - Range Sum Query 2D Mutable | Binary Indexed Tree
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28 Apple 22
28.5K Views
Medium-High Frequency
~35 min Avg. Time
982 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen