Rotate a 2D matrix.
MediumUnlock detailed company stats for this questionUpgrade
You're given an n x n matrix that represents an image. Rotate it 90 degrees clockwise, in place: modify matrix directly instead of creating another matrix. The function doesn't return anything.
Example 1
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Example 2
Input: matrix = [[1, 2], [3, 4]] Output: [[3, 1], [4, 2]]
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
Approach
A clockwise rotation moves the element at (r, c) to (c, n - 1 - r). Writing that directly needs either a second matrix or careful four-way swaps around each ring. Two simpler in-place operations get the same result. Transposing the matrix swaps (r, c) with (c, r). Reversing each row then moves (c, r) to (c, n - 1 - r), which is exactly where a clockwise rotation puts it.
Steps
- Transpose: for every
rand everyc > r, swapmatrix[r][c]withmatrix[c][r]. - Reverse each row.
Complexity
- Time:
O(n²). Each element is moved a constant number of times. - Space:
O(1).
Common mistakes
- Swapping every pair during the transpose, including
c < r. Each pair gets swapped twice, so the matrix ends up unchanged. Only loop overc > r. - Reversing each column instead of each row. That rotates the matrix counterclockwise.
Interview experiences
2 sharedRelated questions
01 MatrixRelated courses

Course

Course
Course

