matrix · high
Rotate a Matrix 90 deg
Rotating a square matrix 90 degrees clockwise in place is a classic (LeetCode 48): transpose the matrix, then reverse each row. Transpose maps (i,j) to (j,i) and the row reversal maps column j to n-1-j, so composed they send (i,j) to (j, n-1-i) — exactly a clockwise rotation. It runs in O(n^2) time with O(1) extra space. Counter-clockwise is transpose then reverse each column, and 180 degrees is reversing the row order then reversing each row.
Rotate a square matrix 90 deg clockwise in place by transposing then reversing each row, which sends (i,j) to (j,n-1-i); O(n^2) time, O(1) space. CCW = transpose + reverse columns; 180 = reverse rows + reverse each row.
The code
// Rotate a square matrix 90 degrees CLOCKWISE, in place.// Trick: transpose, then reverse each row.for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) std::swap(a[i][j], a[j][i]); // 1) transposefor (int i = 0; i < n; ++i) std::reverse(a[i].begin(), a[i].end()); // 2) reverse each rowWhat this lesson walks through
- 01Rotate 90° CW — top row → right column
- 02Pass 1 — transpose (swap across diagonal)
- 03Pass 2 — reverse each row → rotated
Rotating a square matrix 90° clockwise sends the top row to the rightmost column: [1,2,3] ends up as the right column read top-to-bottom. The elegant trick avoids index gymnastics — do it in two simple passes.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Rotate a Matrix 90 deg and 100+ animated C++ interview lessons.