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 INPUT 2D Grid (3x3) 1 1 1 1 0 1 1 1 1 grid = [ [1,1,1], [1,0,1], [1,1,1]] Green=1, Red=0 ALGORITHM STEPS 1 Precompute Arrays Count consecutive 1s left and up from each cell 2 Check Each Cell As bottom-right corner of potential square 3 Validate Border Check all 4 sides have enough consecutive 1s 4 Track Maximum Update max side length when valid square found any Border must be 1s FINAL RESULT 1 1 1 1 0 1 1 1 1 Output: 9 Side = 3 Area = 3 x 3 = 9 OK - Valid 1-bordered square! Key Insight: Precompute two arrays: one storing consecutive 1s to the LEFT of each cell, another storing consecutive 1s ABOVE each cell. Then for each potential square size, verify all four borders have sufficient consecutive 1s in O(1) time. Interior values don't matter - only the border counts! TutorialsPoint - Largest 1-Bordered Square | Optimal Solution O(m*n*min(m,n))
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