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
Understanding the Visualization
1
Input
3×3 zero matrix and query [1,1,2,2]
2
Process
Increment rectangle from (1,1) to (2,2)
3
Output
Matrix with 2×2 submatrix incremented
Key Takeaway
🎯 Key Insight: Use difference arrays to mark boundaries efficiently rather than updating every cell individually
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code