Find the Minimum Area to Cover All Ones I - Problem
Find the Minimum Area to Cover All Ones I

You are given a 2D binary grid where each cell contains either 0 or 1. Your task is to find the smallest possible rectangle that can enclose all the 1s in the grid.

Think of it as finding the tightest bounding box around all the "active" cells. The rectangle must have horizontal and vertical sides (axis-aligned), and you need to return the minimum possible area of such a rectangle.

Goal: Calculate the area of the smallest axis-aligned rectangle that contains all 1s
Input: A 2D binary array grid
Output: An integer representing the minimum area

Input & Output

example_1.py โ€” Basic Rectangle
$ Input: grid = [[0,1,0],[1,0,1]]
โ€บ Output: 6
๐Ÿ’ก Note: The 1s are at positions (0,1), (1,0), and (1,2). The minimum rectangle covers from row 0 to row 1 and from column 0 to column 2, giving us area = (1-0+1) ร— (2-0+1) = 2 ร— 3 = 6.
example_2.py โ€” Single Row
$ Input: grid = [[1,0],[0,0]]
โ€บ Output: 1
๐Ÿ’ก Note: There's only one 1 at position (0,0). The minimum rectangle is just this single cell with area = 1 ร— 1 = 1.
example_3.py โ€” Full Coverage
$ Input: grid = [[1,1],[1,1]]
โ€บ Output: 4
๐Ÿ’ก Note: All cells contain 1s. The minimum rectangle must cover the entire grid, so area = 2 ร— 2 = 4.

Constraints

  • 1 โ‰ค grid.length, grid[i].length โ‰ค 100
  • grid[i][j] is either 0 or 1
  • There is at least one 1 in grid

Visualization

Tap to expand
Photo Cropping AnalogyOriginal Photo๐Ÿ“ท๐Ÿ“ท๐Ÿ“ทminColmaxColminRowmaxRowPerfect Crop๐Ÿ“ท๐Ÿ“ท๐Ÿ“ทAlgorithm Steps:1. minRow = 35, maxRow = 165, minCol = 25, maxCol = 2652. Height = maxRow - minRow + 1 = 1313. Width = maxCol - minCol + 1 = 2414. Cropped Area = 131 ร— 241 = 31,571 pixelsJust like photo cropping, we find the tightest boundaries around all important content!๐ŸŽฏ Key Insight: The optimal rectangle is always defined by the extreme positions of 1s
Understanding the Visualization
1
Scan the Photo
Go through every pixel in the image systematically
2
Mark Important Objects
When we find an important object (1), note its position
3
Track Extremes
Keep track of the topmost, bottommost, leftmost, and rightmost objects
4
Draw Crop Rectangle
The perfect crop is defined by these extreme boundaries
Key Takeaway
๐ŸŽฏ Key Insight: The minimum bounding rectangle is always determined by the four extreme positions (top, bottom, left, right) where 1s appear. We don't need to check every possible rectangle - just find these boundaries!
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
52.0K Views
Medium-High Frequency
~12 min Avg. Time
1.9K 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