Bird
Raised Fist0
Interview Prepdp-grid-intervalsmediumFacebookAmazonApple

Maximal Square

Choose your preparation mode4 modes available
📋
Problem

Imagine you are designing a photo editing app that needs to detect the largest square area of a certain color in an image grid to apply a filter efficiently.

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

1 ≤ number of rows ≤ 3001 ≤ number of columns ≤ 300matrix[i][j] is '0' or '1'
Edge cases: Empty matrix → output 0Matrix with all zeros → output 0Matrix with all ones → output n*m (full matrix area)
</>
IDE
def maximalSquare(matrix: list[list[str]]) -> int:public int maximalSquare(char[][] matrix)int maximalSquare(vector<vector<char>>& matrix)function maximalSquare(matrix)
def maximalSquare(matrix):
    # Write your solution here
    pass
class Solution {
    public int maximalSquare(char[][] matrix) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int maximalSquare(vector<vector<char>>& matrix) {
    // Write your solution here
    return 0;
}
function maximalSquare(matrix) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for non-empty matrix with '1's due to missing dp updates or incorrect initialization.✅ Initialize max_side to 0 and update dp only when matrix[i][j] == '1'.
Wrong: 1Greedy approach picking first '1' only, ignoring larger squares.✅ Use dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 to find max square side.
Wrong: 9Off-by-one error causing dp to overcount squares in partial matrices.✅ Align dp indices with matrix indices carefully; use dp with extra row and column for base cases.
Wrong: TLEUsing brute force O(m^3) approach on large inputs.✅ Implement O(m*n) DP solution to avoid timeouts.
✓
Test Cases
t1_01basic
Input{"matrix":[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]}
Expected4

The largest square has side length 2, so area = 2*2 = 4.

t1_02basic
Input{"matrix":[["0","1","1","1"],["1","1","1","1"],["0","1","1","1"]]}
Expected9

Largest square side length is 2 (area 4), formed in middle rows and columns.

t2_01edge
Input{"matrix":[]}
Expected0

Empty matrix has no squares, so area is 0.

t2_02edge
Input{"matrix":[["0","0","0"],["0","0","0"]]}
Expected0

All zeros means no square of 1's, so area is 0.

t2_03edge
Input{"matrix":[["1","1","1"],["1","1","1"],["1","1","1"]]}
Expected9

All ones matrix forms a 3x3 square, area = 9.

t3_01corner
Input{"matrix":[["1","1","0","1"],["1","1","1","1"],["0","1","1","1"],["1","1","1","1"]]}
Expected9

Largest square side length 2, area 4; tests greedy approach failure.

t3_02corner
Input{"matrix":[["1","0","1","1"],["1","1","1","1"],["1","1","1","0"],["1","1","0","0"]]}
Expected4

Tests off-by-one errors in dp indexing; largest square side 2, area 4.

t3_03corner
Input{"matrix":[["1"],["1"],["1"],["1"]]}
Expected1

Single column matrix with multiple rows; largest square side 1, area 1.

t4_01performance
Input{"matrix":[["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"]]}
⏱ Performance - must finish in 2000ms

Large 10x30 matrix with all ones; O(m*n) DP must complete within 2s.

Practice

(1/5)
1. You are given a triangular array of numbers where each element can only move to one of the two adjacent numbers in the row below. The goal is to find the minimum sum path from the top to the bottom. Which algorithmic approach guarantees an optimal solution efficiently?
easy
A. Greedy algorithm that picks the minimum adjacent number at each step
B. Divide and conquer by splitting the triangle into two halves and solving independently
C. Pure brute force recursion exploring all paths without memoization
D. Dynamic Programming using bottom-up tabulation to build minimum path sums

Solution

  1. Step 1: Understand problem constraints and properties

    The problem requires finding a minimum path sum with overlapping subproblems and optimal substructure, which suits dynamic programming.
  2. Step 2: Identify suitable algorithm

    Bottom-up DP tabulation efficiently computes minimum sums from the bottom row up, avoiding recomputation and ensuring optimality.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP tabulation solves overlapping subproblems efficiently [OK]
Hint: DP bottom-up tabulation ensures optimal substructure [OK]
Common Mistakes:
  • Assuming greedy choice is always optimal
  • Using brute force recursion without memoization
  • Trying to split triangle independently ignoring dependencies
2. Consider the following snippet from the optimal Zuma Game solution. Given board = "WRRBBW" and hand = "RB", what is the return value of findMinStep(board, hand)?
easy
A. 2
B. -1
C. 3
D. 1

Solution

  1. Step 1: Trace initial calls with board="WRRBBW" and hand="RB"

    Hand has 1 R and 1 B. The board requires more balls to clear groups of 3, but hand is insufficient to clear all.
  2. Step 2: Check if any insertion sequence clears board

    Trying to insert R or B balls to form groups of 3 fails due to insufficient balls; no sequence clears the board fully.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Return -1 indicates no solution with given hand [OK]
Hint: Insufficient hand balls cause no solution -> -1 [OK]
Common Mistakes:
  • Assuming partial removals suffice to clear board
  • Miscounting balls needed for group removal
  • Forgetting to restore hand counts after recursion
3. The following code snippet is a near-correct implementation of the Cherry Pickup DP solution. Identify the line containing the subtle bug that can cause incorrect cherry counting or invalid states.
for step in range(1, 2 * (n - 1) + 1):
    for r1 in range(max(0, step - (n - 1)), min(n, step + 1)):
        c1 = step - r1
        if c1 < 0 or c1 >= n:
            continue
        for r2 in range(max(0, step - (n - 1)), min(n, step + 1)):
            c2 = step - r2
            if c2 < 0 or c2 >= n:
                continue
            if grid[r1][c1] == -1 or grid[r2][c2] == -1:
                continue
            candidates = []
            if r1 > 0 and r2 > 0:
                candidates.append(dp[r1 - 1][c1][r2 - 1])
            if r1 > 0 and c2 > 0:
                candidates.append(dp[r1 - 1][c1][r2])
            if c1 > 0 and r2 > 0:
                candidates.append(dp[r1][c1 - 1][r2 - 1])
            if c1 > 0 and c2 > 0:
                candidates.append(dp[r1][c1 - 1][r2])
            best_prev = max(candidates) if candidates else -float('inf')
            if best_prev == -float('inf'):
                continue
            val = best_prev + grid[r1][c1]
            if r1 != r2:
                val += grid[r2][c2]
            dp[r1][c1][r2] = max(dp[r1][c1][r2], val)
medium
A. Lines appending candidates from dp states without verifying step synchronization
B. Line adding grid[r2][c2] to val when r1 != r2
C. Line checking if grid[r1][c1] == -1 or grid[r2][c2] == -1
D. Line initializing dp with -float('inf') for all states

Solution

  1. Step 1: Examine candidate state transitions

    The candidates appended correspond to previous dp states, but the code does not ensure both players have taken the same number of steps, leading to invalid states.
  2. Step 2: Identify the bug

    Not verifying that the previous states correspond to the same step count causes incorrect cherry counting or index errors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Ensuring step synchronization is critical for correctness [OK]
Hint: Check if previous states align on step count [OK]
Common Mistakes:
  • Double counting cherries when players overlap
  • Ignoring thorn cells early
  • Using 4D dp instead of 3D
4. What is the time complexity of the space-optimized bottom-up dynamic programming solution for the Unique Paths problem on an m x n grid?
medium
A. O(m^2 * n^2)
B. O(m + n)
C. O(m * n * min(m, n))
D. O(m * n)

Solution

  1. Step 1: Identify loops in the code

    The solution uses two nested loops: outer loop runs m-1 times, inner loop runs n-1 times.
  2. Step 2: Calculate total operations

    Total operations ≈ (m-1) * (n-1) -> O(m * n). No extra hidden loops or recursion stack.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Nested loops over m and n -> O(m*n) [OK]
Hint: Nested loops over m and n -> O(m*n) [OK]
Common Mistakes:
  • Confusing with recursion exponential time
  • Forgetting loops multiply complexity
5. Suppose the Cherry Pickup problem is modified so that players can revisit cells multiple times (i.e., cycles allowed), and cherries are replenished after being picked (can be collected multiple times). Which of the following algorithmic changes correctly adapts the solution to this variant?
hard
A. Use the same 3D DP with memoization but remove the check that prevents revisiting cells.
B. Apply a greedy approach that always moves players to the next cell with the highest cherry count.
C. Use a 4D DP tracking both players' full positions and number of visits per cell to avoid double counting.
D. Switch to a shortest path algorithm like Dijkstra on a state graph representing both players' positions and steps, allowing cycles.

Solution

  1. Step 1: Understand the impact of allowing revisits and replenished cherries

    Cycles and replenished cherries mean the problem is no longer acyclic and DP assumptions break down.
  2. Step 2: Identify suitable algorithm

    Modeling the problem as a shortest path on a state graph with both players' positions and steps allows handling cycles and repeated cherry collection correctly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP fails with cycles; shortest path algorithms handle repeated states [OK]
Hint: Cycles break DP; use graph shortest path [OK]
Common Mistakes:
  • Removing DP constraints without changing algorithm
  • Adding dimensions to DP without handling cycles
  • Using greedy which ignores global optimality
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard