Arrays · Matrix Techniques

Matrix Rotation via Transpose

Rotating a square matrix 90 degrees by transposing it, then reversing each row - two simple O(1)-space passes instead of tracking rotated coordinates directly.

  • 5 min read
  • 11 practice questions
  • 2 graded problems
On this page
  1. Description
  2. The approach
  3. A second flavor: which axis you reverse decides the direction
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

Rotating a square matrix by 90 degrees in place is easiest as two simple moves. First transpose it, flipping it along the main diagonal. Then reverse each row, or reverse the order of the rows for the other direction. Each move is easy to check on its own, and that's the point. A one-formula version that moves every cell straight to its final place is much easier to get subtly wrong.

We'll go from simple to more technical:

  1. The pattern: transpose, then reverse.
  2. A second flavor: which axis you reverse decides the direction.
  3. Where composing simple transforms is how real image and matrix code is built.
  4. The mistakes that produce a plausible but wrong matrix.

The approach

Transposing swaps rows and columns: the value at row r, column c moves to row c, column r. The first column becomes the first row. Reversing each row then makes that row read from the other end. Together they give a clockwise turn.

With letters, so you can follow each one:

RowOriginalAfter transposingAfter reversing each row (clockwise)
0a b ca d gg d a
1d e fb e hh e b
2g h ic f ii f c

Check it: after a clockwise turn, the left column a d g, read from the bottom up, becomes the top row g d a.

Java

// Transpose: swap across the main diagonal (only the upper triangle needs visiting).
for (int r = 0; r < n; r++)
    for (int c = r + 1; c < n; c++) {
        int tmp = matrix[r][c];
        matrix[r][c] = matrix[c][r];
        matrix[c][r] = tmp;
    }

// Reverse each row in place.
for (int[] row : matrix)
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        int tmp = row[i]; row[i] = row[j]; row[j] = tmp;
    }

Python

# Transpose: swap across the main diagonal (only the upper triangle needs visiting).
for r in range(n):
    for c in range(r + 1, n):
        matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]

# Reverse each row in place.
for row in matrix:
    row.reverse()

The transpose loop starts c at r + 1, so it visits only the cells above the diagonal. Each pair is swapped exactly once.

A second flavor: which axis you reverse decides the direction

The transpose is the same for both directions. Only the second move changes. For counterclockwise, reverse the order of the rows and leave each row's contents alone:

Java

// Counterclockwise: transpose, then reverse the ORDER of rows (not each row's own contents).
for (int r = 0; r < n / 2; r++) {
    int[] tmp = matrix[r];
    matrix[r] = matrix[n - 1 - r];
    matrix[n - 1 - r] = tmp;
}

Python

# Counterclockwise: transpose, then reverse the ORDER of rows (not each row's own contents).
for r in range(n // 2):
    matrix[r], matrix[n - 1 - r] = matrix[n - 1 - r], matrix[r]

The transposed letters a d g / b e h / c f i become c f i / b e h / a d g. Mixing the two up doesn't crash or make garbage. It produces a perfectly valid rotation in the other direction, which is why the bug is easy to miss.

Where you'll see it

Image and matrix libraries are built this way. A thumbnail rotation, for example, is assembled from small steps such as transpose and flip, each tested on its own. Breaking one hard transform into two easy ones is a habit worth keeping well beyond matrices.

Which tool for which job?

You needUse
90 degrees clockwise, in placetranspose, then reverse each row
90 degrees counterclockwise, in placetranspose, then reverse the row order
180 degreesreverse the row order and each row
Fewest writes, in placefour-way cycles, layer by layer
A non-square matrixa new n x m matrix: out[c][rows-1-r] = m[r][c]
A quick copy in Pythonzip(*m[::-1])

Common mistakes

MistakeWhat happensDo this instead
Transposing every pair (c from 0)each pair is swapped twice; nothing changesc from r + 1
Reversing the wrong axisthe opposite rotationtrace a 2x2 by hand
Reversing without transposinga reflection, not a rotationtranspose first
Rotating a non-square matrix in placeit doesn't fitallocate the rotated shape
Off-by-one in the four-way cyclecells land in the wrong ringloop i from layer to n - 2 - layer

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. A transpose loop visits every pair (r, c), not just those with c > r. What happens?

Show answer

Each pair is swapped, then swapped back when the loop reaches its mirror image. The matrix ends exactly as it started, with no error and no sign that anything went wrong.

2. For a counterclockwise turn, a solution transposes and then reverses each row. What's the result?

Show answer

A valid 90-degree rotation, but clockwise. Nothing crashes and nothing looks broken. Only a test with distinct values in a known layout can tell the two directions apart.

3. Transpose-then-reverse makes two passes. Why prefer it to a one-pass index formula?

Show answer

Each pass is simple, well known and easy to check on its own. A single combined formula has to get every index and offset right at once, with nothing to check halfway. The extra pass is a small cost; a wrong formula is easy to write and hard to spot.

Key takeaways

  • Rotate in two passes: transpose, then reverse. No index formula is needed.
  • Transpose only the cells above the diagonal (c > r), or every swap is undone.
  • After the transpose, reversing each row turns clockwise; reversing the row order turns counterclockwise.
  • Every bug here gives a believable matrix rather than a crash. Test with distinct values you can check by hand.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
Clockwise, in placetranspose + reverse each row
Counterclockwisetranspose + reverse the row order
180 degreesreverse rows and row order
Fewest writesfour-way cycles
Non-squarea new n x m matrix

Snippets worth knowing by heart

Java

for (int r = 0; r < n; r++)
    for (int c = r + 1; c < n; c++) {          // upper triangle only
        int t = m[r][c]; m[r][c] = m[c][r]; m[c][r] = t;
    }
for (int[] row : m)
    for (int i = 0, j = n - 1; i < j; i++, j--) {   // reverse each row: clockwise
        int t = row[i]; row[i] = row[j]; row[j] = t;
    }

Python

n = len(m)
for r in range(n):
    for c in range(r + 1, n):                  # upper triangle only
        m[r][c], m[c][r] = m[c][r], m[r][c]
for row in m:
    row.reverse()                              # clockwise; m.reverse() instead for counterclockwise

The traps

  • c from 0 in the transpose: every pair is swapped twice, so nothing changes. Start c at r + 1.
  • The wrong axis reversed: you rotate the opposite way. Trace a 2x2 by hand.
  • No transpose: reversing alone gives a reflection, not a rotation. Transpose first.
  • Non-square in place: the rotated shape doesn't fit. Allocate a new matrix.
  • Ring bounds in the four-way cycle: cells land in the wrong ring. Loop i from layer to n - 2 - layer.

Staff-level points, one line each

  • Two reflections make a rotation: (r, c) → (c, n-1-r).
  • A square has 8 symmetries, all built from transpose and reversals.
  • 1,000 x 1,000: 1,999,000 writes (two passes) vs 1,000,000 (four-way cycles).
  • 2 x 3 rotated clockwise: [[4, 1], [5, 2], [6, 3]].
  • Large transposes work in cache-sized blocks.

Say it in an interview

  • "A clockwise rotation is a transpose followed by reversing each row."
  • "I only swap the upper triangle so each pair moves once."
  • "It's O(n^2) time and O(1) extra space."
  • "The four-way cycle does half the writes, but this is easier to verify."

Practice

This skill comes with 11 multiple-choice questions that tell you which misconception a wrong answer reveals and 2 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Matrix Rotation via Transpose free

Rotate Matrix

MediumProCoding problemJava · Python

Turn an n x n matrix a quarter turn clockwise, in place.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Rotate Matrix Counterclockwise

MediumProCoding problemJava · Python

Given an n x n 2D matrix, rotate it by 90 degrees counterclockwise, in place.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Matrix Rotation via Transpose free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime