Range Sum Query 2D - Immutable

MediumMatrixprefix 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 receive a fixed 2D integer grid and then many queries, each asking for the sum of all cells inside an axis-aligned rectangle. Implement: - NumMatrix(matrix) receives the m x n grid. - sumRegion(row1, col1, row2, col2) returns the sum of every matrix[r][c] with row1 <= r <= row2 and col1 <= c <= col2 (both corners inclusive). The grid never changes. After O(m·n) preprocessing, each query must run in O(1).

Examples

Input: ["NumMatrix","sumRegion","sumRegion","sumRegion","sumRegion"] [[[[2,0,-1],[4,3,1],[-2,5,6]]],[0,0,1,1],[1,1,2,2],[0,2,2,2],[2,0,2,0]]
Output: [null,9,15,6,-2]
Top-left 2x2 is 2+0+4+3 = 9. Bottom-right 2x2 is 3+1+5+6 = 15. The last column is -1+1+6 = 6. Cell (2,0) alone is -2.
Input: ["NumMatrix","sumRegion"] [[[[7]]],[0,0,0,0]]
Output: [null,7]
A 1x1 grid has one possible region.

Constraints

  • 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`.

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