MediumNo. 1139

Largest 1-Bordered Square — LeetCode 1139 Python Solution

Topics
Array, Dynamic Programming, Matrix
Reading time
4 min

The 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.

Example

Input
grid = [[1,1,1],[1,0,1],[1,1,1]]
Output
9

Python solution

PythonSolution
class Solution:
    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        down = [[0] * n for _ in range(m)]
        right = [[0] * n for _ in range(m)]
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                if grid[i][j]:
                    down[i][j] = down[i + 1][j] + 1 if i + 1 < m else 1
                    right[i][j] = right[i][j + 1] + 1 if j + 1 < n else 1
        for k in range(min(m, n), 0, -1):
            for i in range(m - k + 1):
                for j in range(n - k + 1):
                    if (
                        down[i][j] >= k
                        and right[i][j] >= k
                        and right[i + k - 1][j] >= k
                        and down[i][j + k - 1] >= k
                    ):
                        return k * k
        return 0

Complexity

Time
O(m × n × min(m, n))
Space · auxiliary
O(m × n)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1139. Largest 1-Bordered Square is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0174Dungeon GameHard
0221Maximal SquareMedium
0329Longest Increasing Path in a MatrixHard

Frequently asked questions

How hard is LeetCode 1139. Largest 1-Bordered Square?

LeetCode 1139. Largest 1-Bordered Square is rated Medium on LeetCode.

What is the time complexity of LeetCode 1139. Largest 1-Bordered Square?

The Python solution on this page runs in O(m × n × min(m, n)).

What is the space complexity of LeetCode 1139. Largest 1-Bordered Square?

The Python solution on this page uses O(m × n) auxiliary space.

What topics does LeetCode 1139. Largest 1-Bordered Square cover?

LeetCode 1139. Largest 1-Bordered Square is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.