Range Sum Query 2D - Mutable

HardMatrixprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a 2D integer grid matrix. Support point updates and rectangle-sum queries interleaved in any order. - NumMatrix(matrix) stores the grid. - update(row, col, val) **sets** matrix[row][col] to val (it replaces the value; it does not add). - sumRegion(row1, col1, row2, col2) returns the sum of all cells in the rectangle with top-left corner (row1, col1) and bottom-right corner (row2, col2), both corners **inclusive**. With many calls of each kind, aim for O(log m * log n) per operation, for example with a 2D Fenwick tree.

Examples

Input: ["NumMatrix","sumRegion","update","sumRegion","sumRegion"] [[[[1,2,3],[4,5,6],[7,8,9]]],[0,0,1,1],[1,1,0],[0,0,1,1],[1,0,2,2]]
Output: [null,12,null,7,34]
The top-left 2x2 block is 1 + 2 + 4 + 5 = 12. After the 5 becomes 0 it sums to 7. The bottom two rows now sum to 4 + 0 + 6 + 7 + 8 + 9 = 34.
Input: ["NumMatrix","sumRegion","update","sumRegion"] [[[[5]]],[0,0,0,0],[0,0,-3],[0,0,0,0]]
Output: [null,5,null,-3]
A 1x1 grid: the update replaces 5 with -3.

Constraints

  • `1 <= m, n <= 200`, where the grid is `m x n`.
  • `-1000 <= matrix[i][j], val <= 1000`
  • `0 <= row1 <= row2 < m`, `0 <= col1 <= col2 < n`
  • At most 5000 calls to `update` and `sumRegion` combined.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems