Maximum size square sub-matrix with all 1s

Pattern: 2D grid DP

medium

The largest all-1 square ending at a cell (as its bottom-right corner) is 1 more than the smallest of the squares ending above it, to its left and diagonally above-left.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a binary matrix, return the side length of the largest square made only of 1s. The catalogue has no practice link for this one. LeetCode's Maximal Square returns the area instead.

Think first

  • If a cell is 0, how big is a square ending there?
  • What limits a square ending at a 1?
  • Why the minimum of three?

Hints

    Brute force, and why it fails

    For every cell, grow a square while all cells are 1: O((R × C)²).

    The key insight

    Each cell's square depends on three neighbours, so one pass finds them all.

    Dry run

    side2

    A 1 at (r, c) with neighbours 2 (above), 2 (left) and 1 (diagonal) gets 1 + min = 2.

    Step 1 of 2

    The plan

    side[r][c] = 0 if mat is 0 else 1 + min(side[r-1][c], side[r][c-1], side[r-1][c-1])
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    One pass; one row is enough.

    Edge cases

    • All 0s: 0.
    • All 1s: the smaller dimension.
    • One row.
    I've built my logic, show the code

    Java

    class Solution {
        public int maxSquare(int[][] mat) {
            int R = mat.length, C = mat[0].length, best = 0;
            int[][] side = new int[R + 1][C + 1];   // side[r][c]: the biggest all-1 square ending at cell (r - 1, c - 1)
            for (int r = 1; r <= R; r++)
                for (int c = 1; c <= C; c++)
                    if (mat[r - 1][c - 1] == 1) {   // limited by the squares above, to the left and diagonally
                        side[r][c] = 1 + Math.min(side[r - 1][c - 1], Math.min(side[r - 1][c], side[r][c - 1]));
                        best = Math.max(best, side[r][c]);
                    }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int maxSquare(vector<vector<int>>& mat) {
            int R = static_cast<int>(mat.size()), C = static_cast<int>(mat[0].size()), best = 0;
            vector<vector<int>> side(R + 1, vector<int>(C + 1, 0));   // the biggest all-1 square ending at (r - 1, c - 1)
            for (int r = 1; r <= R; r++)
                for (int c = 1; c <= C; c++)
                    if (mat[r - 1][c - 1] == 1) {   // limited by the squares above, to the left and diagonally
                        side[r][c] = 1 + min(side[r - 1][c - 1], min(side[r - 1][c], side[r][c - 1]));
                        best = max(best, side[r][c]);
                    }
            return best;
        }
    };

    Python

    class Solution:
        def maxSquare(self, mat: list[list[int]]) -> int:
            C = len(mat[0])
            prev, best = [0] * (C + 1), 0           # side lengths of the biggest all-1 squares ending in the previous row
            for row in mat:
                cur = [0] * (C + 1)
                for c in range(1, C + 1):
                    if row[c - 1] == 1:             # limited by the squares above, to the left and diagonally
                        cur[c] = 1 + min(prev[c - 1], prev[c], cur[c - 1])
                        best = max(best, cur[c])
                prev = cur
            return best

    Common mistakes

    • Returning the area instead of the side.
    • Forgetting the diagonal.

    Similar problems