DSA problem
Increment Submatrices by One
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] = [row1_i, col1_i, row2_i, col2_i], you should do the following operation:
Add 1 to every element in the submatrix with the upper-left corner (row1_i, col1_i) and the lower-right corner (row2_i, col2_i). That is, add 1 to mat[x][y] for all row1_i <= x <= row2_i and col1_i <= y <= col2_i.
Return the matrix mat after performing every query.
Naively applying each query touches up to n^2 cells. Instead, use a 2D difference array: each rectangle update is recorded as four O(1) corner adjustments, and a final 2D prefix-sum pass over the difference array reconstructs the answer.
Examples
n = 3, queries = [[1,1,2,2],[0,0,1,1]][[1,1,0],[1,2,1],[0,1,1]]n = 2, queries = [[0,0,1,1]][[1,1],[1,1]]Constraints
- 1 <= n <= 500
- 1 <= queries.length <= 10^4
- 0 <= row1_i <= row2_i < n
- 0 <= col1_i <= col2_i < n
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.