The problem. Given an m × n binary matrix of "0"s and "1"s, find the largest square made only of 1s and return its area.
matrix = [["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]] -> 4
matrix = [["0","1"],["1","0"]] -> 1
matrix = [["0"]] -> 0Let side[r][c] be the side of the largest all-ones square whose bottom-right corner is (r, c). If the cell is 0, it's 0. If it's 1, the square can grow only as far as its three neighbours allow — the squares ending to the left, above and above-left each limit it — so side[r][c] = 1 + min(left, above, above-left). The answer is the largest side anywhere, squared.
function maximalSquare(matrix) { const m = matrix.length, n = matrix[0].length; let best = 0; for (let r = 0; r < m; r++) { for (let c = 0; c < n; c++) { let k = 0; // try sides 1, 2, ... with top-left (r, c) grow: while (r + k < m && c + k < n) { for (let i = 0; i <= k; i++) { // check the new bottom row and right column if (matrix[r + k][c + i] !== "1" || matrix[r + i][c + k] !== "1") break grow; } k++; } best = Math.max(best, k); } } return best * best;}Time O(m · n · min(m, n)²), space O(1). Each corner grows its square one ring at a time.
Each 1 extends the smallest of the three squares touching it.
function maximalSquare(matrix) { const m = matrix.length, n = matrix[0].length; const side = Array.from({ length: m }, () => new Array(n).fill(0)); let best = 0; for (let r = 0; r < m; r++) { for (let c = 0; c < n; c++) { if (matrix[r][c] !== "1") continue; // a 0 ends every square if (r === 0 || c === 0) side[r][c] = 1; // on the edge: a 1x1 square at most else side[r][c] = 1 + Math.min(side[r - 1][c], side[r][c - 1], side[r - 1][c - 1]); best = Math.max(best, side[r][c]); } } return best * best;}Time O(m · n), space O(m · n) — or O(n) with one row plus a variable remembering the old above-left value. Why the minimum? A square of side s at (r, c) needs squares of side s − 1 ending at all three neighbours; the smallest neighbour is the limit.
"1", not 1.side[r][c] instead of taking the max.