Find the Minimum Area to Cover All Ones II - Problem
You're given a 2D binary grid containing 0s and 1s. Your mission is to find exactly 3 non-overlapping rectangles that together cover all the 1s in the grid with the minimum total area.
Think of this as placing three rectangular stickers on a grid to cover all the marked spots (1s) while using as little sticker material as possible. The rectangles:
- Must have non-zero areas (can't be empty)
- Cannot overlap each other
- Are allowed to touch at edges
- Must have horizontal and vertical sides (axis-aligned)
Goal: Return the minimum possible sum of areas of these three rectangles.
Input & Output
example_1.py — Basic Grid
$
Input:
grid = [[1,0,1],[1,1,1]]
›
Output:
5
💡 Note:
We can place 3 rectangles: (0,0)-(0,0) covering grid[0][0]=1 with area 1, (0,2)-(0,2) covering grid[0][2]=1 with area 1, and (1,0)-(1,2) covering the bottom row with area 3. Total area = 1+1+3 = 5.
example_2.py — Sparse Grid
$
Input:
grid = [[1,0,1,0],[0,1,0,1]]
›
Output:
5
💡 Note:
Optimal placement uses 3 rectangles: (0,0)-(0,0) for grid[0][0], (0,2)-(1,3) covering the right portion, and (1,1)-(1,1) for grid[1][1]. This gives areas 1+4+1 = 6. Better solution: use vertical strips.
example_3.py — Clustered Pattern
$
Input:
grid = [[1,1],[1,1]]
›
Output:
4
💡 Note:
All 1s form a 2×2 cluster. We need exactly 3 rectangles with non-zero areas. Minimum is to use three 1×1 rectangles covering 3 cells (area=3) plus one 1×1 rectangle covering the remaining cell (area=1), but we need exactly 3. Optimal: split into regions giving total area 4.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Target Area
Find the minimal bounding box containing all 1s (important locations)
2
Strategic Cuts
Try different ways to partition this area: 3 horizontal strips, 3 vertical strips, or mixed approaches
3
Optimize Each Region
For each partition, find the smallest rectangle that covers all 1s in that region
4
Compare Strategies
Test all partitioning strategies and return the one with minimum total area
Key Takeaway
🎯 Key Insight: Instead of trying all possible rectangle combinations, strategically partition the grid using cuts and solve optimally for each region, reducing complexity from exponential to polynomial time.
Time & Space Complexity
Time Complexity
O(m⁶n⁶)
For each of 3 rectangles, we need O(m²n²) possible rectangles, leading to exponential combinations
✓ Linear Growth
Space Complexity
O(1)
Only storing current best result and temporary variables
✓ Linear Space
Constraints
- 1 ≤ grid.length ≤ 30
- 1 ≤ grid[0].length ≤ 30
- grid[i][j] is either 0 or 1
- At least 1 cell contains 1
- The grid will always have a valid solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code