Increment Submatrices by One - Problem

You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes.

You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation:

Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom right corner (row2i, col2i). That is, add 1 to mat[x][y] for all row1i <= x <= row2i and col1i <= y <= col2i.

Return the matrix mat after performing every query.

Input & Output

Example 1 — Basic Rectangle Update
$ Input: n = 3, queries = [[1,1,2,2]]
Output: [[0,0,0],[0,1,1],[0,1,1]]
💡 Note: Start with 3×3 zero matrix. Query [1,1,2,2] increments submatrix from (1,1) to (2,2), so cells [1,1], [1,2], [2,1], [2,2] become 1.
Example 2 — Multiple Overlapping Queries
$ Input: n = 2, queries = [[0,0,1,1],[0,0,0,0]]
Output: [[2,1],[1,1]]
💡 Note: First query increments entire 2×2 matrix. Second query increments only cell (0,0). Final: (0,0) has value 2, others have value 1.
Example 3 — Single Cell Update
$ Input: n = 2, queries = [[1,1,1,1]]
Output: [[0,0],[0,1]]
💡 Note: Query targets only cell (1,1), incrementing it from 0 to 1. All other cells remain 0.

Constraints

  • 1 ≤ n ≤ 500
  • 1 ≤ queries.length ≤ 104
  • queries[i].length == 4
  • 0 ≤ row1i ≤ row2i < n
  • 0 ≤ col1i ≤ col2i < n

Visualization

Tap to expand
Increment Submatrices by One INPUT Initial Matrix (n=3) 0 0 0 0 0 0 0 0 0 0 1 2 0 1 2 Query: [row1=1, col1=1, row2=2, col2=2] Submatrix to increment: ALGORITHM STEPS 1 Parse Query Extract (1,1) to (2,2) 2 Mark Boundaries Use difference array 0 0 0 0 0 +1 0 -1 0 0 0 0 0 -1 0 +1 3 Prefix Sum Row-wise then col-wise 4 Extract Result Return n x n matrix FINAL RESULT Updated Matrix 0 0 0 0 1 1 0 1 1 Output: [[0,0,0], [0,1,1],[0,1,1]] OK - Verified Key Insight: Use 2D difference array technique: mark +1 at top-left corner, -1 at boundaries. Apply prefix sums (row-wise then column-wise) to get final values in O(n^2 + q) time. This avoids O(q * n^2) brute force by batching all query effects before computing result. TutorialsPoint - Increment Submatrices by One | Optimal Solution (Difference Array)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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