MediumNo. 0764

Largest Plus Sign — LeetCode 764 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

The problem

You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines.

Example

Input
n = 5, mines = [[4,2]]
Output
2
Explanation
In the above grid, the largest plus sign can only be of order 2. One of them is shown.

Python solution

PythonSolution
class Solution:
    def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
        dp = [[n] * n for _ in range(n)]
        for x, y in mines:
            dp[x][y] = 0
        for i in range(n):
            left = right = up = down = 0
            for j, k in zip(range(n), reversed(range(n))):
                left = left + 1 if dp[i][j] else 0
                right = right + 1 if dp[i][k] else 0
                up = up + 1 if dp[j][i] else 0
                down = down + 1 if dp[k][i] else 0
                dp[i][j] = min(dp[i][j], left)
                dp[i][k] = min(dp[i][k], right)
                dp[j][i] = min(dp[j][i], up)
                dp[k][i] = min(dp[k][i], down)
        return max(max(v) for v in dp)

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 764. Largest Plus Sign is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0773Sliding PuzzleHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium

Frequently asked questions

How hard is LeetCode 764. Largest Plus Sign?

LeetCode 764. Largest Plus Sign is rated Medium on LeetCode.

What topics does LeetCode 764. Largest Plus Sign cover?

LeetCode 764. Largest Plus Sign is tagged Array and Dynamic Programming 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.