#3537
Fill a Special Grid
MediumArrayDivide and ConquerMatrixDivide and ConquerRecursion
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)
Utilize recursion to fill quadrants systematically, ensuring the special conditions are met without redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Define a recursive function to fill the grid based on the current quadrant size.
- 2Step 2: Calculate the starting number for the current quadrant and fill it with the appropriate range of numbers.
- 3Step 3: Recursively call the function for each quadrant, adjusting the starting number accordingly.
solution.py18 lines
1# Full working Python code
2
3def fill_grid(n):
4 size = 2 ** n
5 grid = [[0] * size for _ in range(size)]
6 def fill(x, y, size, start):
7 if size == 1:
8 grid[x][y] = start
9 return start + 1
10 mid = size // 2
11 start = fill(x, y + mid, mid, start)
12 start = fill(x + mid, y + mid, mid, start)
13 start = fill(x + mid, y, mid, start)
14 return fill(x, y, mid, start)
15 fill(0, 0, size, 0)
16 return grid
17
18print(fill_grid(2))ℹ
Complexity note: The recursive approach efficiently fills the grid in O(n) time by leveraging the structure of quadrants.
- 1Recursive structure mirrors the grid's quadrant division.
- 2Each quadrant can be treated independently while maintaining overall constraints.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.