#2536
Increment Submatrices by One
MediumArrayMatrixPrefix SumDifference ArrayPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n² * q) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
Instead of updating each element in the submatrix directly, we can use a difference array approach to mark the increments efficiently. This allows us to perform all updates in constant time and then compute the final matrix in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a difference matrix of size (n+1) x (n+1) filled with zeros.
- 2Step 2: For each query, increment the top-left corner and decrement the position just outside the bottom-right corner to mark the range for updates.
- 3Step 3: Convert the difference matrix back to the final matrix using a prefix sum approach.
solution.py15 lines
1def incrementSubmatrices(n, queries):
2 diff = [[0] * (n + 1) for _ in range(n + 1)]
3 for row1, col1, row2, col2 in queries:
4 diff[row1][col1] += 1
5 diff[row1][col2 + 1] -= 1
6 diff[row2 + 1][col1] -= 1
7 diff[row2 + 1][col2 + 1] += 1
8 mat = [[0] * n for _ in range(n)]
9 for i in range(n):
10 for j in range(n):
11 mat[i][j] = diff[i][j]
12 if i > 0: mat[i][j] += mat[i - 1][j]
13 if j > 0: mat[i][j] += mat[i][j - 1]
14 if i > 0 and j > 0: mat[i][j] -= mat[i - 1][j - 1]
15 return matℹ
Complexity note: The time complexity is O(n²) for the final matrix computation, while the space complexity is O(n) due to the additional difference matrix used for updates.
- 1Using a difference matrix allows for efficient range updates.
- 2Prefix sums help in converting the difference matrix back to the final matrix.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.