Browse curriculum

Rotate Image

Rotate the matrix by 90 degrees clockwise in-place.

Problem Understanding

Turn an n x n matrix, an image stored as a grid of pixels, a quarter turn clockwise. The rotation must happen in-place, inside the same matrix, without allocating a second one.

Strategy (Transpose + Reflect)

  1. Transpose: Swap matrix[i][j] with matrix[j][i].
  2. Reflect: Reverse each row.
  • Step 1: Transpose converts rows to columns.

  • Step 2: Reversing rows fixes the left-right order for 90 deg rotation.

Interactive Visualization

See the two-step process: Transpose then Reverse.

Dry Run

Matrix: [[1,2],[3,4]]

Step Action State
1 Transpose [[1,3],[2,4]] (Swap 2 & 3)
2 Reverse Row 0 [[3,1],[2,4]]
3 Reverse Row 1 [[3,1],[4,2]]

Result: 90 deg clockwise rotation.

Edge Cases & Checks

Validation points:

  • Square Matrix: Problem usually guarantees n x n. If not, this method fails.

  • Clockwise vs Counter: For Counter-Clockwise, Reverse then Transpose.

Solution

O(N^2) Time, O(1) Space.

Rotate Image Code
1var rotate = function(matrix) {
2 const n = matrix.length;
3 // Transpose
4 for (let i = 0; i < n; i++) {
5 for (let j = i; j < n; j++) {
6 [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
7 }
8 }
9 // Reflect
10 for (let i = 0; i < n; i++) {
11 matrix[i].reverse();
12 }
13};

The approach, step by step

  1. Transpose

    For every i and every j > i, swap matrix[i][j] with matrix[j][i]. Rows become columns.

  2. Reverse every row

    Reverse each row in place. The transposed matrix is now rotated 90° clockwise.

Frequently asked questions

How do you rotate a matrix 90 degrees clockwise in place?

Transpose it by swapping matrix[i][j] with matrix[j][i] for every cell above the diagonal, then reverse each row. Both steps swap values inside the matrix, so no second matrix is needed.


How do you rotate the matrix counter-clockwise instead?

Do the two steps in the other order: reverse each row first, then transpose.


What is the time and space complexity of Rotate Image?

O(n²) time: the transpose visits each cell above the diagonal once and the reversal visits every row. The extra space is O(1), because every change is a swap inside the matrix.

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description