EasyNo. 0598

Range Addition II — LeetCode 598 Python Solution

Topics
Array, Math
Reading time
2 min

The problem

You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. Count and return the number of maximum integers in the matrix after performing all the operations.

Example

Input
m = 3, n = 3, ops = [[2,2],[3,3]]
Output
4
Explanation
The maximum integer in M is 2, and there are four of it in M. So return 4.

Python solution

PythonSolution
class Solution:
    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
        for a, b in ops:
            m = min(m, a)
            n = min(n, b)
        return m * n

Complexity

Time
O(k)where k is the length of the operation array ops
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 598. Range Addition II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0048Rotate ImageMedium
0066Plus OneEasy
0189Rotate ArrayMedium
0204Count PrimesMedium
0335Self CrossingHard
0384Shuffle an ArrayMedium

Frequently asked questions

How hard is LeetCode 598. Range Addition II?

LeetCode 598. Range Addition II is rated Easy on LeetCode.

What is the time complexity of LeetCode 598. Range Addition II?

The Python solution on this page runs in O(k), where k is the length of the operation array \textit{ops}.

What is the space complexity of LeetCode 598. Range Addition II?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 598. Range Addition II cover?

LeetCode 598. Range Addition II is tagged Array and Math 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.

Free to download. Check it runs on your machine, then pick a plan.