#1914
Cyclically Rotating a Grid
MediumArrayMatrixSimulationArrayMatrix
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 approach focuses on reducing the number of rotations needed by calculating the effective rotations using modulo. This way, we avoid unnecessary full rotations and directly manipulate the layers.
⚙️
Algorithm
4 steps- 1Step 1: Extract each layer from the grid and store it in a list.
- 2Step 2: Calculate effective rotations using k % length of the layer.
- 3Step 3: Rotate the layer using slicing instead of multiple shifts.
- 4Step 4: Place the rotated layers back into their respective positions in the grid.
solution.py37 lines
1def rotateGrid(grid, k):
2 m, n = len(grid), len(grid[0])
3 layers = []
4 for layer in range(min(m, n) // 2):
5 current_layer = []
6 # Extract layer
7 for i in range(layer, n - layer):
8 current_layer.append(grid[layer][i])
9 for i in range(layer + 1, m - layer):
10 current_layer.append(grid[i][n - layer - 1])
11 for i in range(n - layer - 1, layer - 1, -1):
12 current_layer.append(grid[m - layer - 1][i])
13 for i in range(m - layer - 2, layer, -1):
14 current_layer.append(grid[i][layer])
15 layers.append(current_layer)
16
17 # Rotate each layer
18 for i in range(len(layers)):
19 k_mod = k % len(layers[i])
20 layers[i] = layers[i][-k_mod:] + layers[i][:-k_mod]
21
22 # Place layers back
23 for layer in range(len(layers)):
24 idx = 0
25 for i in range(layer, n - layer):
26 grid[layer][i] = layers[layer][idx]
27 idx += 1
28 for i in range(layer + 1, m - layer):
29 grid[i][n - layer - 1] = layers[layer][idx]
30 idx += 1
31 for i in range(n - layer - 1, layer - 1, -1):
32 grid[m - layer - 1][i] = layers[layer][idx]
33 idx += 1
34 for i in range(m - layer - 2, layer, -1):
35 grid[i][layer] = layers[layer][idx]
36 idx += 1
37 return gridℹ
Complexity note: The time complexity is O(n) because we only traverse each layer once for extraction and placement, and the space complexity is O(n) due to storing the layers.
- 1Understanding layers is crucial for matrix manipulation.
- 2Effective rotation reduces unnecessary computations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.