Algorithms · Visualized

Matrix: Rotate Image

Matrix & 2D

Rotations, traversals, and grid searches on 2D arrays.

Rotates a square matrix 90 degrees clockwise in place, without using a second matrix. Time: O(n²) average, O(n²), where n is the matrix dimension worst; space: O(1) — rotates in place.

Big-O: Classic O(m·n) sweeps and in-place tricks.

Rotate Matrix 90°

Matrix / 2D Array

Rotates a square matrix 90 degrees clockwise in place, without using a second matrix. This is achieved in two simple steps: first transpose the matrix (flip it over its main diagonal, swapping rows and columns), then reverse each row.

How Rotate Image Works

  1. Transpose the matrix: for every cell (i, j) where i < j, swap the value at (i, j) with the value at (j, i) — this flips rows into columns.
  2. After transposing, go through each row of the matrix.
  3. Reverse the order of elements within each row.
  4. Once every row has been reversed, the matrix has been rotated 90 degrees clockwise.
  5. No extra matrix is needed — all changes happen directly on the original matrix.

Rotate Image Worked Example

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

Transpose: [[1,4,7],[2,5,8],[3,6,9]]. Reverse each row: [7,4,1], [8,5,2], [9,6,3]. Final rotated matrix: [[7,4,1],[8,5,2],[9,6,3]].

Matrix: Rotate ImageO(n²)
Rotate an n×n matrix 90° clockwise in place.
7
4
1
8
5
2
9
6
3
Step 1 / 6
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Rotate Image 90° clockwise in place: transpose, then reverse each row.
Python · Matrix Algorithms in Code
def rotate_image(m):
    n = len(m)
    for i in range(n):
        for j in range(i + 1, n):
            m[i][j], m[j][i] = m[j][i], m[i][j]
    for row in m:
        row.reverse()
    return m

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Rotate Image Time & Space Complexity

BestO(n²)
AverageO(n²)
WorstO(n²), where n is the matrix dimension
SpaceO(1) — rotates in place

When to Use Rotate Image

  • Image processing: rotating pixel grids for photo editing or display orientation changes.
  • Game boards and puzzle mechanics (e.g. rotating Tetris pieces, sliding puzzles).

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.