MEDIUM 2-D Dynamic Programming
221. Maximal Square
📖 Problem
Given an m x n binary matrix filled with '0's and '1's, find the largest square containing only '1's and return its area.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Array DP table updates
- •State transition thinking
- •Base case initialization
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Dynamic Programming reasoning pattern
💡 Approach
- → Use dp[i][j] = size of largest square ending at (i,j)
- → If matrix[i][j] is '0', dp[i][j] = 0
- → Otherwise, dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
- → Keep track of max size, return max_size²
- → Time: O(m * n), Space: O(m * n) or O(n) optimized
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •Use dp[i][j] = size of largest square ending at (i,j)
- •If matrix[i][j] is '0', dp[i][j] = 0
- •Otherwise, dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
Common Pitfalls
- •Keep track of max size, return max_size²
- •Time: O(m * n), Space: O(m * n) or O(n) optimized
🧪 Test Cases
Test Case 1
Not run Input:
maximalSquare([['1','0','1','0','1'],['1','0','1','0','1'],['1','0','1','0','1']]); Expected:
1 Test Case 2
Not run Input:
maximalSquare([['0','1'],['1','0']]); Expected:
1 Test Case 3
Not run Input:
maximalSquare(matrix: string[][]); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output