Rotate Image — LeetCode 48 Python Solution
- Problem
- #48
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.
Example
- Input
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- [[7,4,1],[8,5,2],[9,6,3]]
Python solution
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n >> 1):
for j in range(n):
matrix[i][j], matrix[n - i - 1][j] = matrix[n - i - 1][j], matrix[i][j]
for i in range(n):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the side length of the matrix |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 48. Rotate Image is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 48. Rotate Image?
- LeetCode 48. Rotate Image is rated Medium on LeetCode.
- What is the time complexity of LeetCode 48. Rotate Image?
- The Python solution on this page runs in O(n^2), where n is the side length of the matrix.
- What is the space complexity of LeetCode 48. Rotate Image?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 48. Rotate Image cover?
- LeetCode 48. Rotate Image is tagged Array, Math and Matrix on LeetCode.