Algo-Sim › Matrix & Bit Manipulation
Rotate Image
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Rotate an n×n matrix 90° clockwise in place: transpose across the diagonal, then reverse each row.
Problem
Given an n × n matrix, rotate it 90° clockwise. Change the matrix in place rather than allocating a second one.
Constraints
- 1 ≤ n ≤ 20
- -1000 ≤ matrix[i][j] ≤ 1000
- In place: O(1) extra space
Edge cases to test
- 1 × 1 matrix
- 2 × 2 matrix
- Odd n: the centre cell stays put
Follow-up questions
- How do you rotate counter-clockwise?
- Transpose, then reverse each column (or reverse each row first, then transpose). Still O(n²), in place.
- What if the matrix is not square?
- It can’t be rotated in place; build an n × m result with
result[j][m − 1 − i] = a[i][j].
Solution
Java
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for (int[] row : matrix) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int tmp = row[l];
row[l] = row[r];
row[r] = tmp;
}
}
}Python
def rotate(matrix):
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
l, r = 0, n - 1
while l < r:
row[l], row[r] = row[r], row[l]
l += 1
r -= 1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void rotate(vector<vector<int>> &matrix) {
int n = int(matrix.size());
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for (vector<int> &row : matrix) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int tmp = row[l];
row[l] = row[r];
row[r] = tmp;
}
}
}
};
More Matrix & Bit Manipulation problems
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)