Search
⌘K
Get Premium
Matrices

Rotate Image

medium

DESCRIPTION (inspired by Leetcode.com)

Write a function to rotate an n x n 2D matrix representing an image by 90 degrees clockwise. The rotation must be done in-place, meaning you should modify the input matrix directly without using an additional matrix for the operation.

Input:

matrix = [
    [1,4,7],
    [2,5,8],
    [3,6,9]
]

Output:

[
    [3,2,1],
    [6,5,4],
    [9,8,7]
]

Explanation: The matrix is rotated by 90 degrees clockwise, transforming its columns into rows in reverse order.

Explanation

This problem can be done in two steps. We first transpose the matrix, then reverse the elements in each row.

Step 1:

Transpose the matrix by swapping the elements across the diagonal. This can be done in-place by using a nested for loop to swap the elements.
Visualization
def rotate_image(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = \
matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i] = matrix[i][::-1]
return matrix
147258369

n = 3

0 / 12

Step 2:

Reverse the elements in each row of the matrix.
Visualization
def rotate_image(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = \
matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i] = matrix[i][::-1]
return matrix
147258369i = 2j = 2

swap matrix[2][2] and matrix[2][2]

0 / 4

Solution

|
2d-list of integers
Try these examples:
Visualization
def rotate_image(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = \
matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i] = matrix[i][::-1]
return matrix
147258369

rotate image

0 / 17

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n²) where n is the number of rows in the matrix. We need to process each element in the matrix.

Space Complexity: O(1) since we are doing the rotation in-place without using extra space.

Your account is free and you can post anonymously if you choose.

The best mocks on the market.

Now up to 15% off

Learn More
Reading Progress

On This Page