AlgoInsight

DSA problem

Increment Submatrices by One

MediumPrefix SumPattern: 2D Difference Arraytop600AmazonGoogleMicrosoft

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

Example 1
Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]
Output: [[1,1,0],[1,2,1],[0,1,1]]
Explanation: The first query adds 1 to the submatrix from (1,1) to (2,2). The second query adds 1 to the submatrix from (0,0) to (1,1). Overlapping cell (1,1) is incremented twice.
Example 2
Input: n = 2, queries = [[0,0,1,1]]
Output: [[1,1],[1,1]]
Explanation: The single query adds 1 to the entire 2x2 matrix.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumdifference-arraymatrixarray

Browse all DSA problems