Maximal Square — LeetCode 221

Pattern: 2D Dynamic Programming (DP)

Let's follow the same problem-solving template:

  1. Understand the problem through an example
  2. Signal — identify the pattern and constraints
  3. Edge cases
  4. Brute Force — understand the straightforward approach
  5. Optimized Solution — Dynamic Programming
  6. Dry Run — visualize how DP works
  7. Complexity Analysis
  8. Interview explanation

1. Understand the problem through an example

Given a 2D matrix containing only '0' and '1', find the largest square containing only '1' and return its area.

There are three important things to understand:

  1. The square must contain exclusively 1s.
  2. It must have equal width and height.
  3. We return the area, not the side length.

Example

matrix = [
    ["1", "0", "1", "0", "0"],
    ["1", "0", "1", "1", "1"],
    ["1", "1", "1", "1", "1"],
    ["1", "0", "0", "1", "0"]
]

Let's visualize the matrix: