Skip to main content

Rotate Image

Medium Subject: Math & Geometry
Time Complexity
O(N^2)
Space Complexity
O(1)

Problem Description

Problem Statement

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.

Example 1:

  • Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
  • Output: [[7,4,1],[8,5,2],[9,6,3]]

Optimal Solution

Python

Approach: Transpose and Reflect

To rotate 90 degrees clockwise, we can first transpose the matrix (swap matrix[i][j] with matrix[j][i]), and then reflect it horizontally (reverse each row).

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        n = len(matrix)

        # Transpose
        for i in range(n):
            for j in range(i, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

        # Reverse rows
        for i in range(n):
            matrix[i].reverse()