InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Maximal Square

medium Original β†—
Solving tips
  • Reframe globally-to-locally: dp[i][j] = side of the largest all-ones square whose BOTTOM-RIGHT corner is (i,j); the answer is (max side)^2.
  • Recurrence for a '1' cell: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]); it must be min (the square is limited by its weakest supporting neighbor), not max.
  • Return the AREA (square the best side), not the side itself; and compare cells against the string '1'/'0', not integers.
  • Target O(m*n) time, O(n) space with one rolling row plus a saved diag scalar for the overwritten top-left value.

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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.