Range Addition II - 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.

Input & Output

Example 1 — Basic Operations
$ Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
💡 Note: Operation [2,2] increments cells (0,0), (0,1), (1,0), (1,1). Operation [3,3] increments all 9 cells. The intersection (0,0), (0,1), (1,0), (1,1) gets incremented twice, so 4 cells have maximum value.
Example 2 — Empty Operations
$ Input: m = 3, n = 3, ops = []
Output: 9
💡 Note: No operations means all cells remain 0. All 9 cells have the same maximum value of 0.
Example 3 — Single Cell Intersection
$ Input: m = 3, n = 3, ops = [[2,2],[3,3],[1,1]]
Output: 1
💡 Note: The intersection of all operations is min(2,3,1) × min(2,3,1) = 1×1. Only cell (0,0) receives all increments.

Constraints

  • 1 ≤ m, n ≤ 4 × 104
  • 0 ≤ ops.length ≤ 104
  • ops[i].length == 2
  • 1 ≤ ai ≤ m
  • 1 ≤ bi ≤ n

Visualization

Tap to expand
Range Addition II - Optimal Solution INPUT 3x3 Matrix (initialized to 0) 0 0 0 0 0 0 0 0 0 Parameters: m = 3 n = 3 Operations: [2, 2] [3, 3] Op1: rows 0-1, cols 0-1 Op2: rows 0-2, cols 0-2 ALGORITHM STEPS 1 Find Overlap Region All ops affect top-left corner 2 Calculate Min Rows minRow = min(2, 3) = 2 3 Calculate Min Cols minCol = min(2, 3) = 2 4 Result = Area result = 2 * 2 = 4 After all operations: 2 2 1 2 2 1 1 1 1 Dark = Max value (2) FINAL RESULT 2 2 1 2 2 1 1 1 1 Maximum value cells = 4 Output: 4 OK - 4 max integers minRow * minCol = 2 * 2 = 4 Key Insight: Every operation increments a rectangle starting from (0,0). The cells with the maximum value are those covered by ALL operations - the intersection of all rectangles. This is simply min(all ai) * min(all bi). Time: O(k) where k = number of operations | Space: O(1) TutorialsPoint - Range Addition II | Optimal Solution
Asked in
Google 25 Amazon 15 Microsoft 20
32.0K Views
Medium Frequency
~15 min Avg. Time
890 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