Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Google
Increment Submatrices By One

Apply several +1 rectangle updates to a matrix and return the final grid after all increments are accumulated.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Range Add Queries 2D

gfg
Problem Statement

You are given an m×nm \times n matrix initially filled with zeros and a list of update queries.

Each query is a rectangle described by its top-left and bottom-right coordinates. For every query, increment by $1$ every cell inside that submatrix, including the borders.

After processing all queries, return the final matrix.

A direct cell-by-cell simulation for every query may be too slow when the matrix and query count are large, so look for a way to accumulate the updates efficiently.

Input Format

  • An integer matrix size (m,n)(m, n).
  • A list of rectangle updates, where each update is of the form [r1, c1, r2, c2].
  • Coordinates are 0-indexed and inclusive.

Output Format

  • Return an m×nm \times n matrix where each cell contains the total number of rectangle updates that cover it.

Constraints

  • 1m,n1 \le m, n
  • Each query satisfies 0r1r2<m0 \le r1 \le r2 < m and 0c1c2<n0 \le c1 \le c2 < n
  • The number of queries may be large enough that an O(mnq)O(m n q) simulation is inefficient.
Examples
Sample cases returned by the problem API.

Example 1

Input

m = 3, n = 4, queries = [[0,0,1,1],[1,2,2,3]]

Output

[[1,1,0,0],[1,1,1,1],[0,0,1,1]]

Explanation

The first query increments the top-left 2x2 block. The second query increments the bottom-right 2x2 block. Overlapping cells would accumulate if any rectangles overlapped.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.