Range Addition II - Problem
Range Addition II is a clever optimization problem that tests your ability to recognize patterns and avoid unnecessary computation.

You start with an m × n matrix filled entirely with zeros. You're given an array of operations where each operation ops[i] = [ai, bi] means: increment by 1 every cell M[x][y] where 0 ≤ x < ai and 0 ≤ y < bi.

After performing all operations, your task is to count how many cells contain the maximum value in the matrix. The key insight? You don't actually need to simulate the entire matrix!

Example: If m=3, n=3 and ops=[[2,2],[3,3]], the matrix becomes:
[[2,2,1], [2,2,1], [1,1,1]]
The maximum value is 2, appearing in 4 cells, so return 4.

Input & Output

example_1.py — Basic Example
$ Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
💡 Note: After operations: [[2,2,1],[2,2,1],[1,1,1]]. Maximum value is 2, appearing in 4 cells (top-left 2×2 region).
example_2.py — No Operations
$ Input: m = 3, n = 3, ops = []
Output: 9
💡 Note: No operations performed, so all cells remain 0. All 9 cells have the maximum value 0.
example_3.py — Single Operation
$ Input: m = 3, n = 3, ops = [[2,2]]
Output: 4
💡 Note: Only one operation affects the 2×2 top-left region. These 4 cells have value 1, which is the maximum.

Visualization

Tap to expand
Range Addition II VisualizationOperation 1Operation 2Operation 3MAX REGIONKey Insight:✓ Maximum values appear in the intersection of ALL operations✓ No need to simulate the matrix!✓ Just find min(width) × min(height)Algorithm:1. min_a = min(all operation widths)2. min_b = min(all operation heights)3. return min_a × min_bTime: O(k) | Space: O(1)where k = number of operations
Understanding the Visualization
1
Individual Operations
Each operation covers a rectangle from (0,0) to (a-1, b-1)
2
Overlap Detection
Find the common area where ALL rectangles overlap
3
Mathematical Solution
Intersection dimensions = (min_a, min_b), so answer = min_a × min_b
Key Takeaway
🎯 Key Insight: The maximum value cells form a rectangle from (0,0) to (min_a-1, min_b-1). Count = min_a × min_b. No matrix simulation needed!

Time & Space Complexity

Time Complexity
⏱️
O(k)

Single pass through k operations to find minimum dimensions

n
2n
Linear Growth
Space Complexity
O(1)

Only storing two integer variables for minimum dimensions

n
2n
Linear Space

Constraints

  • 1 ≤ m, n ≤ 4 × 104
  • 0 ≤ ops.length ≤ 104
  • ops[i].length == 2
  • 1 ≤ ai ≤ m
  • 1 ≤ bi ≤ n
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
18.8K Views
Medium Frequency
~12 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen