InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Maximal Square

medium Original ↗ 00:00

Problem

Given an m x n binary matrix filled with characters '0' and '1', find the largest square made up entirely of '1's and return its area.

If the matrix contains no '1', return 0.

Examples

  • [["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"]]4 — a 2×2 block of ones (side 2, area 2² = 4) sits in the middle.
  • [["0","1"], ["1","0"]]1 — no 2×2 all-ones block exists, so the best is a single 1 (area 1).
  • [["0"]]0 — no ones at all.

Constraints

  • m == matrix.length, n == matrix[0].length
  • 1 <= m, n <= 300
  • matrix[i][j] is '0' or '1'.

Checking every possible square explicitly is far too slow at 300×300; the expected solution is O(m × n).

Think about it first

Hint 1 Instead of asking "where is the biggest square," ask a local question at each cell: "what is the largest all-ones square whose **bottom-right corner** is exactly here?" The global answer is the biggest of those.
Hint 2 A cell can be the bottom-right corner of a side-`k` square only if the cells directly above, directly left, and diagonally up-left can all support a side-`(k-1)` square. That ties `dp[i][j]` to three neighbors — a 2-D DP.
Hint 3 If `matrix[i][j] == '1'`: `dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])`; otherwise `dp[i][j] = 0`. Track the maximum side seen; the answer is that side squared.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug