#3195
Medium Algorithms Find the minimum area to cover all ones i
Array Matrix
78.2% acceptance
Feb 24, 2026
490
32
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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn minimum_area(grid: Vec<Vec<i32>>) -> i32 {
let rows = grid.len();
let cols = grid[0].len();
let mut min_r = rows;
let mut max_r = 0;
let mut min_c = cols;
let mut max_c = 0;
for r in 0..rows {
for c in 0..cols {
if grid[r][c] == 1 {
if r < min_r { min_r = r; }
if r > max_r { max_r = r; }
if c < min_c { min_c = c; }
if c > max_c { max_c = c; }
}
}
}
((max_r - min_r + 1) * (max_c - min_c + 1)) as i32
}
}