Skip to main content
Medium Matrix High frequency

Rotate Image

Open on LeetCode

Approach Summary

Two-step in-place: first transpose (swap [i][j] and [j][i]), then mirror horizontally (reverse each row).

Full Solution & Approach

Rotating a square matrix 90 degrees clockwise can be decomposed into two simple in-place operations: transpose, then reverse each row. Transposing swaps matrix[i][j] with matrix[j][i] for all i < j — after this, rows and columns have traded places. Reversing every row then produces the exact clockwise rotation. The two-step view is the mental model interviewers look for, and it avoids the error-prone four-way element rotation. A direct four-way rotation also works: for each layer (ring) of the square, rotate the four corners and the intermediate positions cyclically — this is faster in one pass but much easier to get wrong with off-by-one errors at the layer boundaries. The transpose-then-reverse version operates on every element exactly twice with trivial indexing, so it is both correct and simple to explain. For a counter-clockwise rotation the same trick applies with the steps swapped: transpose followed by reversing each column, or equivalently reverse each row first then transpose.

Both steps visit every cell a constant number of times — O(n²) time for an n×n matrix. All operations are swaps in place, so O(1) extra space.

Solution Code

Solution

def rotate(matrix: list[list[int]]) -> None:
    n = len(matrix)
    # Transpose: swap across the main diagonal
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    # Reverse each row
    for row in matrix:
        row.reverse()

Edge Cases to Watch

  • 1×1 matrix — no rotation actually changes it
  • Odd-dimension matrix — the center cell is untouched
  • Repeated values — the rotation still applies cell-by-cell
  • The matrix must be modified in place — the method returns nothing

How to Recognize This Pattern

  • Rotate matrix 90° clockwise in-place
  • Transpose + mirror

Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(1)

Tags

Array Matrix Math

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee