Largest 1-Bordered Square - Problem
You're given a 2D binary grid filled with 0s and 1s. Your task is to find the largest square subgrid where all border cells contain 1s, and return the number of elements in that square.
Think of it like finding the largest picture frame made of 1s - the interior can contain any values, but the entire border must be made of 1s. If no such square exists, return 0.
Key Points:
- Only the border needs to be all
1s - The interior can contain
0s or1s - Return the total number of cells in the largest valid square
- A 1Γ1 square with a
1counts as a valid bordered square
Input & Output
example_1.py β Basic Valid Square
$
Input:
[[1,1,1],[1,0,1],[1,1,1]]
βΊ
Output:
9
π‘ Note:
The 3Γ3 grid has all border cells as 1s (top row: 1,1,1; bottom row: 1,1,1; left column: 1,1,1; right column: 1,1,1). The center cell is 0, but that's allowed since only borders matter. Area = 3Β² = 9.
example_2.py β Multiple Valid Squares
$
Input:
[[1,1,0,0],[1,1,1,1],[1,1,1,1],[0,1,1,1]]
βΊ
Output:
16
π‘ Note:
Multiple squares are possible: 2Γ2 at (0,0), 2Γ2 at (1,1), 3Γ3 at (1,1), and 4Γ4 doesn't work due to incomplete borders. The largest valid square is 4Γ4 starting at (0,1) with all borders being 1s. Area = 4Β² = 16.
example_3.py β No Valid Square
$
Input:
[[1,0,1],[0,1,0],[1,0,1]]
βΊ
Output:
1
π‘ Note:
No square larger than 1Γ1 can be formed because any 2Γ2 or larger square will have 0s in its border. However, individual 1s count as 1Γ1 squares with valid borders. Area = 1Β² = 1.
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Workshop
Examine the grid to identify painted (1) and unpainted (0) blocks
2
Measure Consecutive Blocks
For each position, count how many painted blocks extend right and down
3
Test Frame Sizes
For each corner position, test if frames of various sizes can be built
4
Find Largest Frame
Return the area of the largest valid square frame found
Key Takeaway
π― Key Insight: Pre-computing consecutive painted blocks allows us to validate frame borders instantly, making the algorithm much faster than checking each border cell individually.
Time & Space Complexity
Time Complexity
O(mΓnΓmin(m,n))
O(mΓn) to build DP arrays, then O(mΓn) positions Γ O(min(m,n)) square sizes to check
β Linear Growth
Space Complexity
O(mΓn)
Two auxiliary arrays to store consecutive 1s in right and down directions
β‘ Linearithmic Space
Constraints
- 1 β€ grid.length, grid[i].length β€ 100
- grid[i][j] is 0 or 1
- Only border cells need to be 1s - interior can have any values
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code