#1139
Largest 1-Bordered Square
MediumArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution utilizes dynamic programming to precompute the number of consecutive 1s in each direction (up, left, down, right) for each cell. This allows us to efficiently check the borders of potential squares without redundant checks.
⚙️
Algorithm
4 steps- 1Step 1: Create four auxiliary matrices to store the count of consecutive 1s in the up, left, down, and right directions for each cell.
- 2Step 2: Fill these matrices by iterating through the grid.
- 3Step 3: Iterate through each cell again to determine the maximum size of a square that can be formed with that cell as the bottom-right corner.
- 4Step 4: For each potential square, check if the borders are valid using the precomputed matrices.
solution.py26 lines
1def largest1BorderedSquare(grid):
2 if not grid:
3 return 0
4 rows, cols = len(grid), len(grid[0])
5 up = [[0] * cols for _ in range(rows)]
6 left = [[0] * cols for _ in range(rows)]
7
8 # Fill up and left matrices
9 for r in range(rows):
10 for c in range(cols):
11 if grid[r][c] == 1:
12 up[r][c] = up[r - 1][c] + 1 if r > 0 else 1
13 left[r][c] = left[r][c - 1] + 1 if c > 0 else 1
14
15 max_size = 0
16 # Check for the largest square
17 for r in range(rows):
18 for c in range(cols):
19 if grid[r][c] == 1:
20 size = min(up[r][c], left[r][c])
21 while size > 0:
22 if up[r][c - size + 1] >= size and left[r - size + 1][c] >= size:
23 max_size = max(max_size, size)
24 break
25 size -= 1
26 return max_size * max_sizeℹ
Complexity note: The time complexity remains O(n²) due to the need to fill the matrices and check for squares. The space complexity is O(n) because we store additional matrices for up and left counts, which is proportional to the size of the input grid.
- 1Understanding how to check borders efficiently can save time.
- 2Dynamic programming can help reduce redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.