#764

Largest Plus Sign

Medium
ArrayDynamic ProgrammingDynamic ProgrammingGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

Instead of checking each cell multiple times, we can preprocess the grid to count how many consecutive 1's are in each direction for every cell. This allows us to compute the maximum order of the plus sign in constant time for each cell.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create four matrices (left, right, up, down) to store the count of consecutive 1's in each direction for each cell.
  2. 2Step 2: Populate these matrices by iterating through the grid in all four directions.
  3. 3Step 3: For each cell, calculate the possible order of the plus sign as the minimum of the counts from the four matrices.
  4. 4Step 4: Track the maximum order found.
solution.py24 lines
1def orderOfLargestPlusSign(n, mines):
2    grid = [[1] * n for _ in range(n)]
3    for x, y in mines:
4        grid[x][y] = 0
5    left = [[0] * n for _ in range(n)]
6    right = [[0] * n for _ in range(n)]
7    up = [[0] * n for _ in range(n)]
8    down = [[0] * n for _ in range(n)]
9    for r in range(n):
10        for c in range(n):
11            if grid[r][c] == 1:
12                left[r][c] = (left[r][c-1] + 1) if c > 0 else 1
13                up[r][c] = (up[r-1][c] + 1) if r > 0 else 1
14    for r in range(n-1, -1, -1):
15        for c in range(n-1, -1, -1):
16            if grid[r][c] == 1:
17                right[r][c] = (right[r][c+1] + 1) if c < n-1 else 1
18                down[r][c] = (down[r+1][c] + 1) if r < n-1 else 1
19    max_order = 0
20    for r in range(n):
21        for c in range(n):
22            if grid[r][c] == 1:
23                max_order = max(max_order, min(left[r][c], right[r][c], up[r][c], down[r][c]))
24    return max_order

Complexity note: The time complexity remains O(n²) due to the need to process each cell in the grid, but we use additional space for the four direction matrices.

  • 1The center of the plus sign must be a 1, and the arms must extend in all four directions without hitting a 0.
  • 2Using preprocessing (direction counts) allows for efficient calculation of the plus sign order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.