In the Increment Submatrices by One coding problem, you are given an matrix initially filled with zeros. You receive a series of queries, where each query provides the coordinates and of a submatrix. For each query, you must increment every cell in that submatrix by 1. After all queries are processed, return the final matrix.
Companies like Meta and Google ask this to test your knowledge of Prefix Sum interview patterns in 2D. A naive solution would iterate through every cell in the submatrix for every query, leading to complexity. Interviewers expect an solution, which demonstrates your ability to use "Difference Arrays" to handle range updates efficiently.
This problem uses the 2D Difference Array or 2D Prefix Sum pattern.
diff[r1][c1] += 1diff[r1][c2+1] -= 1 (if within bounds)diff[r2+1][c1] -= 1 (if within bounds)diff[r2+1][c2+1] += 1 (if within bounds)diff array to get the final values for each cell.
The prefix sum formula: res[i][j] = diff[i][j] + res[i-1][j] + res[i][j-1] - res[i-1][j-1].matrix, Query: (1,1) to (2,2).
diff[1][1] = 1.diff[1][3] = -1 (Stop the row increment).diff[3][1] = -1 (Stop the column increment).diff[3][3] = 1 (Fix the double-subtraction at the corner).Master the 1D difference array first (incrementing range in ). The 2D version is just an extension of that principle. It is a vital technique for any competitive programming or "Hard" level algorithmic interview.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Matrix Block Sum | Medium | Solve | |
| Grid Game | Medium | Solve | |
| Count Submatrices With Equal Frequency of X and Y | Medium | Solve | |
| Count Submatrices with Top-Left Element and Sum Less Than k | Medium | Solve | |
| Largest Magic Square | Medium | Solve |