File: range-addition-ii/solution.py

Date: 2026-06-06

Time: 18:36

Range Addition II — solution.py

Purpose

This file implements and tests LeetCode 598: Range Addition II. It solves the problem of determining how many cells in an m × n matrix contain the maximum value after a series of increment operations, where each operation [ai, bi] increments every cell in the submatrix [0..ai-1][0..bi-1] by 1.

Key Components

Solution.maxCount(m, n, ops) — The core algorithm. Takes matrix dimensions and a list of operations, returns the count of cells holding the maximum value.

The insight: every operation increments the top-left rectangle [0..ai-1][0..bi-1]. The cell that receives *all* increments is the one in the intersection of *every* rectangle — which is the rectangle defined by the minimum ai and minimum bi across all operations. The maximum value lives exactly in that overlap region, so the answer is mina * minb.

TestMaxCount — Eight test cases covering edge conditions: empty ops (entire matrix), single operation, full-matrix operations, degenerate 1×1 overlap, and single-row/single-column matrices.

Patterns

Dependencies

Imports: unittest (stdlib), List from typing (type annotation only).

Imported by: The "Imported By" list in the prompt is misleading — those are *other* test files in sibling problem directories, not actual consumers of this module's code. Each problem folder is independent; the cross-references likely come from a shared test harness (run_tests.py) or static analysis that picked up the common Solution class name.

Flow

1. If ops is empty → return m * n (all cells are zero, all are maximal).

2. Compute min_a = minimum of all op[0] values across operations.

3. Compute min_b = minimum of all op[1] values across operations.

4. Return mina * minb — the area of the intersection rectangle.

The matrix is never materialized. The original m and n parameters are unused when ops is non-empty, because the problem guarantees 1 <= ai <= m and 1 <= bi <= n, so the min values are always within bounds.

Invariants

Error Handling

None. The function trusts its inputs match the LeetCode contract. Empty ops is the only edge case handled explicitly. Passing malformed data (e.g., ops with fewer than 2 elements) would raise an IndexError from op[0]/op[1].

Topics to Explore

Beliefs