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 ArrayRotates 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
- 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.
- After transposing, go through each row of the matrix.
- Reverse the order of elements within each row.
- Once every row has been reversed, the matrix has been rotated 90 degrees clockwise.
- 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]].
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 mBehind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.