↓Skip to main content
  1. LeetCode/

LeetCode 3195: Find the Minimum Area to Cover All Ones I

·1 min· ·
LeetCode Medium Array Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-08-22

  • Submissions: Accepted (first try)

Approach
#

With sides parallel to the grid, the smallest rectangle containing every 1 hugs the outermost ones (Array Template 5): top at the highest row with a 1, bottom at the lowest, and likewise for columns. The area is (max_r - min_r + 1) × (max_c - min_c + 1).

My Solution
#

class Solution:
    def minimumArea(self, grid: List[List[int]]) -> int:
        rows = [i for i, row in enumerate(grid) if 1 in row]
        cols = [j for j in range(len(grid[0])) if any(row[j] for row in grid)]
        return (rows[-1] - rows[0] + 1) * (cols[-1] - cols[0] + 1)

I originally updated the four bounds cell by cell in two nested loops, almost 3 s; here I find the rows containing a 1 and then the columns, and 1 in row is a built-in scan, which is faster.

Complexity
#

Time O(m · n), space O(m + n).

Mistakes to Avoid
#

  • The bounds are inclusive; add 1 to both height and width.

Interview Explanation
#

The smallest rectangle hugs the outermost ones, so I find the top and bottom rows and the left and right columns containing a 1, and multiply the inclusive spans. Time O(mn).

Related

LeetCode 1222: Queens That Can Attack the King
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 1222 note: step outward from the king in eight directions; the first queen met in each direction can attack, with queens in a set for lookups
LeetCode 3070: Count Submatrices with Top-Left Element and Sum Less Than k
·2 mins
LeetCode Medium Array Matrix Prefix-Sum
LeetCode 3070 note: submatrices containing the top-left corner are exactly the 2D prefix sums P[i][j]; count those <= k
LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·2 mins
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 note: count each value on and off the Y, enumerate the Y value a and background value b (a != b), and take the fewest cells to change
LeetCode 240: Search a 2D Matrix II
·2 mins
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
LeetCode 240 note: start at the top-right corner, moving left when larger and down when smaller, eliminating a row or column each step
LeetCode 48: Rotate Image
·2 mins
LeetCode Medium Array Math Matrix
LeetCode 48 note: rotating 90 degrees clockwise is a transpose followed by reversing each row, both in place
LeetCode 417: Pacific Atlantic Water Flow
·3 mins
LeetCode Medium Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 417 note: walk inward from each ocean’s shore to cells no lower than the current one; cells reached from both oceans are the answer