Maximal Square — LeetCode 221
Pattern: 2D Dynamic Programming (DP)
Let's follow the same problem-solving template:
- Understand the problem through an example
- Signal — identify the pattern and constraints
- Edge cases
- Brute Force — understand the straightforward approach
- Optimized Solution — Dynamic Programming
- Dry Run — visualize how DP works
- Complexity Analysis
- 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:
- The square must contain exclusively
1s.
- It must have equal width and height.
- 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: