Increment Submatrices by One — LeetCode 2536 Python Solution

MediumArrayMatrixPrefix Sum
Problem
#2536
Pattern
Prefix Sum
Reading time
4 min

The problem

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.

Example

Input
n = 3, queries = [[1,1,2,2],[0,0,1,1]]
Output
[[1,1,0],[1,2,1],[0,1,1]]
Explanation
The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.

Python solution

Python
class Solution:
    def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
        mat = [[0] * n for _ in range(n)]
        for x1, y1, x2, y2 in queries:
            mat[x1][y1] += 1
            if x2 + 1 < n:
                mat[x2 + 1][y1] -= 1
            if y2 + 1 < n:
                mat[x1][y2 + 1] -= 1
            if x2 + 1 < n and y2 + 1 < n:
                mat[x2 + 1][y2 + 1] += 1

        for i in range(n):
            for j in range(n):
                if i:
                    mat[i][j] += mat[i - 1][j]
                if j:
                    mat[i][j] += mat[i][j - 1]
                if i and j:
                    mat[i][j] -= mat[i - 1][j - 1]
        return mat

Complexity

MeasureComplexity
TimeO(m + n^2), where m and n are the length of \textit{queries} and the given n, respectively
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2536. Increment Submatrices by One is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2536. Increment Submatrices by One?
LeetCode 2536. Increment Submatrices by One is rated Medium on LeetCode.
What is the time complexity of LeetCode 2536. Increment Submatrices by One?
The Python solution on this page runs in O(m + n^2), where m and n are the length of \textit{queries} and the given n, respectively.
What is the space complexity of LeetCode 2536. Increment Submatrices by One?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2536. Increment Submatrices by One cover?
LeetCode 2536. Increment Submatrices by One is tagged Array, Matrix and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview