Largest 1-Bordered Square Problem
Description
LeetCode Problem 1139.
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.
Example 1:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9
Example 2:
Input: grid = [[1,1,0,0]]
Output: 1
Constraints:
1 <= grid.length <= 1001 <= grid[0].length <= 100grid[i][j]is0or1
Solution
Approach: Run Lengths + Try the Largest Side First
A square with top-left corner (i, j) and side k has four sides, and checking each one cell by cell is slow. Instead, precompute for every cell:
right[i][j]: how many consecutive1s start at(i, j)going right,down[i][j]: how many consecutive1s start at(i, j)going down.
Both are filled from the bottom-right corner: if grid[i][j] is 1, then right[i][j] = right[i][j+1] + 1 and down[i][j] = down[i+1][j] + 1; otherwise both are 0.
Now the square is 1-bordered exactly when
right[i][j] >= k(top side) anddown[i][j] >= k(left side),right[i+k-1][j] >= k(bottom side, starting at the bottom-left corner),down[i][j+k-1] >= k(right side, starting at the top-right corner).
Each check is O(1). Try side lengths from min(m, n) down to 1 and every top-left corner that fits; the first square found is the largest, so return k * k. Only the border matters: the inside of the square can contain 0s (Example 1). If the grid has no 1 at all, return 0.
Complexity: O(m · n · min(m, n)) time in the worst case and O(m · n) extra space for the two tables.
class Solution:
def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# down[i][j] / right[i][j]: length of the run of 1s starting at (i, j) going down / right.
down = [[0] * (n + 1) for _ in range(m + 1)]
right = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if grid[i][j] == 1:
down[i][j] = down[i + 1][j] + 1
right[i][j] = right[i][j + 1] + 1
for k in range(min(m, n), 0, -1): # largest side first
for i in range(m - k + 1):
for j in range(n - k + 1):
if (right[i][j] >= k and down[i][j] >= k # top and left sides
and right[i + k - 1][j] >= k # bottom side
and down[i][j + k - 1] >= k): # right side
return k * k
return 0