Skip to content

3195. Find the Minimum Area to Cover All Ones I

Description

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.

 

Example 1:

Input: grid = [[0,1,0],[1,0,1]]

Output: 6

Explanation:

The smallest rectangle has a height of 2 and a width of 3, so it has an area of 2 * 3 = 6.

Example 2:

Input: grid = [[1,0],[0,0]]

Output: 1

Explanation:

The smallest rectangle has both height and width 1, so its area is 1 * 1 = 1.

 

Constraints:

  • 1 <= grid.length, grid[i].length <= 1000
  • grid[i][j] is either 0 or 1.
  • The input is generated such that there is at least one 1 in grid.

 

Solutions

Solution: Greedy

  • Time complexity: O(mn)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {number[][]} grid
 * @return {number}
 */
const minimumArea = function (grid) {
  const m = grid.length;
  const n = grid[0].length;
  let minRow = m - 1;
  let maxRow = 0;
  let minCol = n - 1;
  let maxCol = 0;

  for (let row = 0; row < m; row++) {
    for (let col = 0; col < n; col++) {
      if (!grid[row][col]) continue;

      minRow = Math.min(row, minRow);
      maxRow = Math.max(row, maxRow);
      minCol = Math.min(col, minCol);
      maxCol = Math.max(col, maxCol);
    }
  }

  return (maxRow - minRow + 1) * (maxCol - minCol + 1);
};

Released under the MIT license