1139. Largest 1-Bordered Square
LeetCode 1139. Largest 1-Bordered Square
Description
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: 9Example 2:
Input: grid = [[1,1,0,0]]
Output: 1Constraints:
1 <= grid.length <= 1001 <= grid[0].length <= 100grid[i][j]is0or1
Tags
Dynamic Programming
Solution
For each square, know how many ones are up, left, down, and right of this square. We can use prefix-sum along 2 axes to pre-process for quicker look-up. Now for each square, we can evaluate whether that square is 1-bordered, by checking if the edge length is equal to the sum of the edge elements with prefix-sum in O(1).
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?