#48
Rotate Image
MediumArrayMathMatrixMatrix ManipulationIn-Place Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(n²) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
The optimal solution uses a two-step process: first, we transpose the matrix, and then we reverse each row. This allows us to rotate the matrix in-place without using extra space.
⚙️
Algorithm
2 steps- 1Step 1: Transpose the matrix by swapping matrix[i][j] with matrix[j][i].
- 2Step 2: Reverse each row of the transposed matrix.
solution.py9 lines
1def rotate(matrix):
2 n = len(matrix)
3 # Transpose
4 for i in range(n):
5 for j in range(i + 1, n):
6 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
7 # Reverse each row
8 for i in range(n):
9 matrix[i].reverse()ℹ
Complexity note: The time complexity remains O(n²) due to the two nested loops for transposing and reversing. The space complexity is O(1) because we are modifying the matrix in place.
- 1Rotating a matrix can be achieved through transposition and row reversal.
- 2In-place operations are crucial for optimizing space complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.