Foundation · Module 3 · Lesson 6

Matrix transformation

Transpose, rotate, and mark rows or columns.

15–25 min readLesson 18 of 123

Lesson 18 of 123

1d streak

In-Place Matrix Transformations & 90° Rotation

Rotating an $N \times N$ matrix by $90^\circ$ in-place without allocating a second matrix is a classic interview challenge. The elegant algebraic insight is decomposing a rotation into two simple in-place operations: Transpose and Row Reversal.

Decomposing 90° Clockwise Rotation: Transpose + Reverse Rows
Initial Matrix:
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]

Step 1: Transpose along the main diagonal (swap matrix[i][j] with matrix[j][i]):
[ 1, 4, 7 ]
[ 2, 5, 8 ]
[ 3, 6, 9 ]

Step 2: Reverse each row horizontally:
[ 1, 4, 7 ]  -->  [ 7, 4, 1 ]
[ 2, 5, 8 ]  -->  [ 8, 5, 2 ]
[ 3, 6, 9 ]  -->  [ 9, 6, 3 ]

Result: Clean 90° clockwise rotation in O(n²) time and O(1) auxiliary space!
RotateMatrix.java
public void rotate(int[][] matrix) {
    int n = matrix.length;

    // Step 1: Transpose matrix along main diagonal
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Step 2: Reverse each row
    for (int i = 0; i < n; i++) {
        int left = 0, right = n - 1;
        while (left < right) {
            int temp = matrix[i][left];
            matrix[i][left++] = matrix[i][right];
            matrix[i][right--] = temp;
        }
    }
}

Active Recall Checkpoint

How would you rotate an N x N matrix 90 degrees COUNTER-CLOCKWISE in-place?

Hint: Modify Step 2 of the clockwise pipeline.

Show answer & explanation

Transpose along the main diagonal, then reverse each COLUMN vertically (or reverse each row first, then transpose).

Cost Model

Complexity & Trade-offs

Transform every cell
O(rows × cols)
O(1) in-place when square
The bound follows from the number of states visited and the work performed per transition.

When to use it

  • Contiguous data, strings, matrix grids, and in-place transformations.
  • Problems where indexes encode processed regions.
  • Cache-friendly scans and compact storage.

Common mistakes

  • Using a stale index after insertion, deletion, or a boundary move.
  • Overwriting a value before it has been consumed.
  • Assuming a matrix is square or a string is mutable.

Practice prompts

  • Reproduce the worked Matrix transformation example without looking at the trace.
  • Change one input condition and explain whether the Matrix transformation invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.