Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created August 22, 2025 17:19
Show Gist options
  • Save tatsuyax25/4d7885da3425f89cf09b83497f6b3fea to your computer and use it in GitHub Desktop.
Save tatsuyax25/4d7885da3425f89cf09b83497f6b3fea to your computer and use it in GitHub Desktop.
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.
/**
* @param {number[][]} grid
* @return {number}
*/
var minimumArea = function(grid) {
// Initialize bounds to extreme values
let minRow = Infinity, maxRow = -Infinity;
let minCol = Infinity, maxCol = -Infinity;
// Traverse the grid to find the bounding box of all 1s
for (let r = 0; r < grid.length; r++) {
for (let c= 0; c < grid[0].length; c++) {
if (grid[r][c] === 1) {
minRow = Math.min(minRow, r);
maxRow = Math.max(maxRow, r);
minCol = Math.min(minCol, c);
maxCol = Math.max(maxCol, c);
}
}
}
// If no 1s were found, return 0
if (minRow === Infinity) return 0;
// Calculate area: (height x width)
const height = maxRow - minRow + 1;
const width = maxCol - minCol + 1;
return height * width;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment