Rotate Matrix by 90 Degrees Clockwise
Problem and examples
Given a square matrix of size n x n, rotate the entire matrix by 90 degrees in the clockwise direction. The rotation should be done in-place, meaning no extra matrix should be used for the transformation.
- Each element of the matrix should be repositioned so that after rotation, the first row becomes the last column, the second row becomes the second-last column, and so on.
- If the matrix is empty or has only one element, return it as is.
| Input Matrix | Output Matrix | Description |
|---|---|---|
| [[1,2],[3,4]] | [[3,1],[4,2]] | 2x2 matrix rotated 90° clockwise |
| [[1,2,3],[4,5,6],[7,8,9]] | [[7,4,1],[8,5,2],[9,6,3]] | Standard 3x3 matrix rotation |
| [[1]] | [[1]] | Single element matrix remains unchanged |
| [] | [] | Empty matrix has no elements to rotate |
| [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] | [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] | 4x4 matrix rotated in-place |
Explore Rotate a Matrix by 90 Degrees Clockwise
Load an example or enter your own input. Use the player controls to follow each change.
Understanding the Problem
We are given a square matrix and asked to rotate it 90 degrees clockwise, in-place, meaning we cannot use any additional memory. Rotating the matrix means repositioning its elements such that each element moves to its new position as if the matrix was physically rotated.
Let’s break down what “rotating 90 degrees clockwise” actually means. Imagine rotating a square paper 90 degrees to the right — the top row becomes the rightmost column, the second row becomes the second-to-right column, and so on.
Our goal is to do this transformation using a step-by-step approach that is easy to understand and efficient to implement without using extra space.
Step-by-Step Solution with Example
Step 1: Start with an Example
Consider the following 3x3 matrix:
1 2 3
4 5 6
7 8 9
After rotating 90 degrees clockwise, the matrix should become:
7 4 1
8 5 2
9 6 3
Step 2: Transpose the Matrix
Transposing means converting rows to columns. This is done by swapping elements matrix[i][j] with matrix[j][i] where i < j.
Transpose of the original matrix:
1 4 7
2 5 8
3 6 9
Step 3: Reverse Each Row
After the transpose, we reverse each row to get the final rotated matrix:
- Row 1:
1 4 7→7 4 1 - Row 2:
2 5 8→8 5 2 - Row 3:
3 6 9→9 6 3
Final Matrix:
7 4 1
8 5 2
9 6 3
Step 4: Why This Works
The transpose step turns the matrix’s rows into columns. The reverse step adjusts the order of elements to simulate a 90-degree clockwise rotation. These two operations combined perform the required rotation — efficiently and in-place.
Edge Cases
- Empty Matrix: An empty matrix should return as-is. There’s nothing to rotate.
- 1x1 Matrix: Rotating a single element matrix has no visible effect. It remains unchanged.
- Non-Square Matrix: This solution only works for square matrices (n x n). Applying it to a non-square matrix (e.g., 3x2) will lead to incorrect behavior and should be avoided.
Finally
This in-place method is simple and elegant. It uses two main operations — transpose and reverse — to achieve the rotation. It runs in O(n²) time and uses O(1) extra space, making it optimal for square matrices.
Always validate the input to make sure the matrix is square and not empty, and handle edge cases gracefully. Understanding the transformation steps visually with an example is key to mastering matrix rotation problems.
- Given an
n x nsquare matrix. - Step 1: Transpose the matrix: swap
matrix[i][j]withmatrix[j][i]for alli < j. - Step 2: Reverse each row of the matrix.
- The matrix is now rotated 90 degrees clockwise.
Implementation and efficiency
C implementation
#include <stdio.h>
void transpose(int matrix[3][3], int n) {
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;
}
}
}
void reverseRows(int matrix[3][3], int n) {
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;
left++;
right--;
}
}
}
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
transpose(matrix, 3);
reverseRows(matrix, 3);
printf("Rotated Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}C++ implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void rotateMatrix(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 (int i = 0; i < n; ++i) {
reverse(matrix[i].begin(), matrix[i].end());
}
for (const auto& row : matrix) {
for (int val : row) cout << val << " ";
cout << endl;
}
}
int main() {
vector<vector<int>> mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
rotateMatrix(mat);
return 0;
}Python implementation
def rotate_matrix(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:
row.reverse()
return matrix
mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotated = rotate_matrix(mat)
for row in rotated:
print(row)Java implementation
public class RotateMatrix {
public static void rotate(int[][] matrix) {
int n = matrix.length;
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;
}
}
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;
left++;
right--;
}
}
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
rotate(mat);
for (int[] row : mat) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
}
}JavaScript implementation
function rotateMatrix(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let row of matrix) {
row.reverse();
}
return matrix;
}
let mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log("Rotated Matrix:", rotateMatrix(mat));Go implementation
package main
import (
"fmt"
)
func rotate(matrix [][]int) {
n := len(matrix)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
}
}
for i := 0; i < n; i++ {
for j := 0; j < n/2; j++ {
matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]
}
}
}
func main() {
mat := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
rotate(mat)
for _, row := range mat {
fmt.Println(row)
}
}Rust implementation
fn rotate_matrix(matrix: &mut Vec<Vec<i32>>) {
let n = matrix.len();
for i in 0..n {
for j in (i + 1)..n {
let temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for row in matrix.iter_mut() {
row.reverse();
}
}
fn main() {
let mut mat = vec![
vec![1, 2, 3],
vec![4, 5, 6],
vec![7, 8, 9],
];
rotate_matrix(&mut mat);
for row in mat.iter() {
println!("{:?}", row);
}
}Kotlin implementation
fun rotateMatrix(matrix: Array<IntArray>) {
val n = matrix.size
for (i in 0 until n) {
for (j in i + 1 until n) {
val temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}
for (row in matrix) {
row.reverse()
}
}
fun main() {
val mat = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6),
intArrayOf(7, 8, 9)
)
rotateMatrix(mat)
for (row in mat) {
println(row.joinToString(" "))
}
}Swift implementation
func rotateMatrix(_ matrix: inout [[Int]]) {
let n = matrix.count
for i in 0..<n {
for j in i+1..<n {
matrix[i][j] ^= matrix[j][i]
matrix[j][i] ^= matrix[i][j]
matrix[i][j] ^= matrix[j][i]
}
}
for i in 0..<n {
matrix[i].reverse()
}
}
var mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotateMatrix(&mat)
for row in mat {
print(row)
}TypeScript implementation
function rotateMatrix(matrix: number[][]): number[][] {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let row of matrix) {
row.reverse();
}
return matrix;
}
let mat: number[][] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log("Rotated Matrix:", rotateMatrix(mat));