Rotate a matrix by 90 degrees

Medium

Problem

Rotate an n × n matrix by 90 degrees clockwise, in place.

Example 1

Input:  [[1,2,3], [4,5,6], [7,8,9]]
Output: [[7,4,1], [8,5,2], [9,6,3]]

Also asked as: Rotate matrix by 90 degrees

Test cases

Case 1

Input:    [[1,2,3],[4,5,6],[7,8,9]]
Expected: [[7,4,1],[8,5,2],[9,6,3]]

Case 2

Input:    [[1]]
Expected: [[1]]

Case 3

Input:    [[1,2],[3,4]]
Expected: [[3,1],[4,2]]

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Transpose, then reverse each row

Time O(n²)Space O(1)

Transposing swaps rows/columns; reversing each row then gives a clockwise 90° rotation. In place.

function rotate(m) {
const n = m.length;
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
[m[i][j], m[j][i]] = [m[j][i], m[i][j]];
for (const row of m) row.reverse();
return m;
}

Counter-clockwise: reverse each row first, then transpose (or reverse the row order after transpose).