Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Matrix High frequency Solution Available Practice Mode

Maximal Square LeetCode Solution

Tags: #Array #Dynamic Programming #Matrix

Approach Summary

dp[i][j] = side length of largest square with bottom-right at (i,j). dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 if cell is 1.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Matrix Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Matrix pattern.

Framework: Matrix • Interview Prep: Tested at FAANG • Explore all Matrix problems & invariants →

How to Recognize This Pattern

  • "Largest square containing only 1s"
  • Min of three neighbours limits the square you can extend

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(m × n)

Tags

Array Dynamic Programming Matrix

Frequently Asked Questions

What is the optimal time and space complexity for Maximal Square?
The optimal solution for Maximal Square achieves O(m × n) runtime complexity and requires O(m × n) auxiliary space. Time Complexity: O(m × n) — each element or state is traversed and evaluated in bounded amortized time without redundant reprocessing. Space Complexity: O(m × n) — allocated for auxiliary tracking structures, recursion call stack, or state caches.
How do I identify that Maximal Square requires the Matrix pattern?
In technical interviews, look for key problem signals: "Largest square containing only 1s"; Min of three neighbours limits the square you can extend. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Matrix strategy.
What critical edge cases must be handled in Maximal Square?
Essential edge cases to verify include: Key recognition trigger: "Largest square containing only 1s".; Constraint condition: Min of three neighbours limits the square you can extend.; Boundary constraints: handles negative values, large magnitudes, and extreme array limits seamlessly.; Suboptimal inputs: runs strictly within the O(m × n) time budget without stack overflow or time limit exceeded.. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Maximal Square?
Maximal Square is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Apple, Airbnb.
Buy me a coffee
Daily Practice
0/0