Find the Minimum Area to Cover All Ones I - Problem

You are given a 2D binary array grid. Find a rectangle with horizontal and vertical sides with the smallest area, such that all the 1's in grid lie inside this rectangle.

Return the minimum possible area of the rectangle.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[0,1,0],[1,1,0]]
Output: 4
💡 Note: The 1's are at positions (0,1), (1,0), and (1,1). The minimum rectangle must cover rows 0-1 and columns 0-1, giving area = 2 * 2 = 4
Example 2 — Single Cell
$ Input: grid = [[1]]
Output: 1
💡 Note: Only one 1 at position (0,0), so minimum rectangle is 1x1 with area = 1
Example 3 — Scattered 1's
$ Input: grid = [[1,0,0],[0,0,1]]
Output: 6
💡 Note: 1's at (0,0) and (1,2). Rectangle must cover rows 0-1 and columns 0-2, giving area = 2 * 3 = 6

Constraints

  • 1 ≤ grid.length, grid[i].length ≤ 100
  • grid[i][j] is 0 or 1

Visualization

Tap to expand
Minimum Area to Cover All Ones INPUT 2D Binary Grid 0 1 0 1 1 0 r=0 r=1 c=0 c=1 c=2 Positions of 1's: (0, 1) - row 0, col 1 (1, 0) - row 1, col 0 (1, 1) - row 1, col 1 Input: grid = [[0,1,0],[1,1,0]] ALGORITHM STEPS 1 Initialize Boundaries minR=INF, maxR=-INF minC=INF, maxC=-INF 2 Scan All Cells For each cell with value 1, update boundaries 3 Find Boundaries minR=0, maxR=1 minC=0, maxC=1 4 Calculate Area height = maxR - minR + 1 width = maxC - minC + 1 Formula: Area = (maxR-minR+1) * (maxC-minC+1) Area = (1-0+1)*(1-0+1) = 4 FINAL RESULT Minimum Bounding Rectangle 0 1 0 1 1 0 width = 2 height = 2 Area Calculation: 2 x 2 = 4 Output: 4 Key Insight: The minimum rectangle covering all 1's is defined by the extreme coordinates (min/max row and column). Time: O(m*n) single pass | Space: O(1) - only store 4 boundary values. No need to construct the rectangle! TutorialsPoint - Find the Minimum Area to Cover All Ones I | Boundary Coordinates Approach
Asked in
Google 25 Amazon 20 Microsoft 15
23.2K 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