Leetcode #2536: Increment Submatrices by One
In this guide, we solve Leetcode #2536 Increment Submatrices by One in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Matrix, Prefix Sum
Intuition
Range queries become simple once we precompute cumulative sums.
We can transform subarray conditions into prefix comparisons.
Approach
Compute prefix sums and use a map to find matching prefixes.
This avoids nested loops while keeping the logic clear.
Steps:
- Compute prefix sums.
- Use a map to find valid ranges.
- Update the answer.
Example
Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]
Output: [[1,1,0],[1,2,1],[0,1,1]]
Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
Python Solution
class Solution:
def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
mat = [[0] * n for _ in range(n)]
for x1, y1, x2, y2 in queries:
mat[x1][y1] += 1
if x2 + 1 < n:
mat[x2 + 1][y1] -= 1
if y2 + 1 < n:
mat[x1][y2 + 1] -= 1
if x2 + 1 < n and y2 + 1 < n:
mat[x2 + 1][y2 + 1] += 1
for i in range(n):
for j in range(n):
if i:
mat[i][j] += mat[i - 1][j]
if j:
mat[i][j] += mat[i][j - 1]
if i and j:
mat[i][j] -= mat[i - 1][j - 1]
return mat
Complexity
The time complexity is , where and are the length of and the given , respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.