Rotate Image

Transpose then reverse each row — a 90-degree clockwise rotation in O(1) extra space.

Medium
Time O(n^2) Space O(1)
LeetCode
2 min read
matrix in-place

Problem#

Rotate an n x n 2D matrix 90 degrees clockwise, in place.

Examples#

  • [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]
  • [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]][[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Constraints#

  • n == matrix.length == matrix[i].length, 1 <= n <= 20.

Approach#

First transpose (swap matrix[i][j] with matrix[j][i] for j > i), then reverse each row. The composition is identical to a 90-degree clockwise rotation.

Solution#

Rotate Image
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
swap(matrix[i][j], matrix[j][i]);
for (auto& row : matrix) reverse(row.begin(), row.end());
}
};

Editorial#

Transpose flips across the main diagonal; reversing each row then mirrors horizontally. Geometrically, a diagonal flip followed by a horizontal flip equals a 90-degree clockwise rotation.

Complexity#

  • Time: O(n^2).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.