#3195

Find the Minimum Area to Cover All Ones I

Medium
ArrayMatrixBounding BoxGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution involves finding the minimum and maximum coordinates of all the 1's in the grid. This allows us to define a single rectangle that covers all the 1's without needing to check every possible rectangle.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize variables to track the minimum and maximum row and column indices of 1's.
  2. 2Step 2: Iterate through the grid to find the coordinates of all 1's, updating the min and max indices as needed.
  3. 3Step 3: Calculate the area of the rectangle defined by these min and max indices.
solution.py13 lines
1# Full working Python code
2
3def minArea(grid):
4    rows, cols = len(grid), len(grid[0])
5    min_row, max_row, min_col, max_col = rows, -1, cols, -1
6    for r in range(rows):
7        for c in range(cols):
8            if grid[r][c] == 1:
9                min_row = min(min_row, r)
10                max_row = max(max_row, r)
11                min_col = min(min_col, c)
12                max_col = max(max_col, c)
13    return (max_row - min_row + 1) * (max_col - min_col + 1)

Complexity note: The time complexity is O(n) because we only need to traverse the grid once to find the coordinates of all 1's. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Finding the bounding box of all 1's is crucial for minimizing the area.
  • 2Iterating through the grid to find min and max coordinates is efficient.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.