Largest 1-Bordered Square - Problem

Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.

A square subgrid has all 1s on its border if all the cells on the top, bottom, left, and right edges are 1s. The interior of the square can contain any values.

Input & Output

Example 1 — Perfect Border Square
$ Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9
💡 Note: The entire 3×3 grid has all 1s on its border (edges), with interior cell [1][1] = 0. This forms a valid 1-bordered square of size 9.
Example 2 — Multiple Small Squares
$ Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,1],[0,0,1,1]]
Output: 4
💡 Note: We can find 2×2 squares at positions (0,0) and (2,2), each having all border cells as 1s. Maximum area is 2×2 = 4.
Example 3 — No Valid Square
$ Input: grid = [[1,0,1],[0,1,0],[1,0,1]]
Output: 1
💡 Note: No square larger than 1×1 has all 1s on its border. The maximum valid square has area 1.

Constraints

  • 1 ≤ grid.length, grid[i].length ≤ 15
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Largest 1-Bordered Square ProblemInput Grid111101111Check Border111101111Valid!9Area = 3×3Orange cells = border (must all be 1)Gray cell = interior (can be 0 or 1)🎯 Key Insight: Only border cells matter for validation
Understanding the Visualization
1
Input Grid
2D grid with 0s and 1s
2
Find Borders
Check if square borders contain only 1s
3
Output Size
Return area of largest valid square
Key Takeaway
🎯 Key Insight: Only the border cells need to be 1s - interior cells can have any values
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen