Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] Output: 4
Example 2:
Input: matrix = [["0","1"],["1","0"]] Output: 1
Example 3:
Input: matrix = [["0"]] Output: 0
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j] is '0' or '1'.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
[["0","1"],["1","0"]]
[["0"]]
maximal-rectangle)largest-plus-sign)count-artifacts-that-can-be-extracted)stamping-the-grid)maximize-area-of-square-hole-in-grid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #221: Maximal Square
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int mx = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') {
dp[i + 1][j + 1] = Math.min(Math.min(dp[i][j + 1], dp[i + 1][j]), dp[i][j]) + 1;
mx = Math.max(mx, dp[i + 1][j + 1]);
}
}
}
return mx * mx;
}
}
// Accepted solution for LeetCode #221: Maximal Square
func maximalSquare(matrix [][]byte) int {
m, n := len(matrix), len(matrix[0])
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
mx := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == '1' {
dp[i+1][j+1] = min(min(dp[i][j+1], dp[i+1][j]), dp[i][j]) + 1
mx = max(mx, dp[i+1][j+1])
}
}
}
return mx * mx
}
# Accepted solution for LeetCode #221: Maximal Square
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
mx = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i + 1][j], dp[i][j]) + 1
mx = max(mx, dp[i + 1][j + 1])
return mx * mx
// Accepted solution for LeetCode #221: Maximal Square
// #Medium #Array #Dynamic_Programming #Matrix #Dynamic_Programming_I_Day_16
// #Top_Interview_150_Multidimensional_DP #Big_O_Time_O(m*n)_Space_O(m*n)
// #2024_09_10_Time_16_ms_(88.89%)_Space_9.3_MB_(81.48%)
impl Solution {
pub fn maximal_square(matrix: Vec<Vec<char>>) -> i32 {
let m = matrix.len();
if m == 0 {
return 0;
}
let n = matrix[0].len();
if n == 0 {
return 0;
}
// Create a 2D dp vector initialized to 0
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_side = 0;
for i in 0..m {
for j in 0..n {
if matrix[i][j] == '1' {
// Calculate the size of the square ending at (i, j)
dp[i + 1][j + 1] = 1 + dp[i][j].min(dp[i + 1][j]).min(dp[i][j + 1]);
max_side = max_side.max(dp[i + 1][j + 1]);
}
}
}
// Return the area of the largest square
(max_side * max_side) as i32
}
}
// Accepted solution for LeetCode #221: Maximal Square
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #221: Maximal Square
// class Solution {
// public int maximalSquare(char[][] matrix) {
// int m = matrix.length, n = matrix[0].length;
// int[][] dp = new int[m + 1][n + 1];
// int mx = 0;
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// if (matrix[i][j] == '1') {
// dp[i + 1][j + 1] = Math.min(Math.min(dp[i][j + 1], dp[i + 1][j]), dp[i][j]) + 1;
// mx = Math.max(mx, dp[i + 1][j + 1]);
// }
// }
// }
// return mx * mx;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.