Rotate Image
MediumMatrix
You get an n × n matrix, a square picture. Turn it 90 degrees clockwise: the first row becomes the last column, the second row the column before it, and so on.
Change matrix itself, without building a second matrix; the function returns nothing. The tests read matrix after your function returns.
Examples
Input: matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]] Output: [[14, 8, 2], [16, 10, 4], [18, 12, 6]]
The top row 2, 4, 6 becomes the right column, read top to bottom.
Input: matrix = [[1, 2], [3, 4]] Output: [[3, 1], [4, 2]]
Each corner moves one corner clockwise: 1 goes to the top right, 2 to the bottom right.
Constraints
1 ≤ n ≤ 20-1000 ≤ matrix[i][j] ≤ 1000
Stuck?
Hint 1
A clockwise turn is two simple moves done in place: flip the matrix over its main diagonal, then mirror it left to right.
Hint 2
Transpose by swapping matrix[i][j] with matrix[j][i] for j > i only, then reverse each row. Reversing the order of the rows instead turns it the other way.
The idea
A quarter turn clockwise is two flips done in place. Flip the matrix over its main diagonal, so rows become columns, then mirror each row left to right. After the first flip the first row sits in the first column, and the mirror moves it to the last column, which is where a clockwise turn puts it.
Time O(n²)Extra space O(1)
Try it again with the idea in mind, or go through the code one step at a time.
The code, step by step
Step 1 of 3
Visit each cell above the main diagonal once. j starts at i + 1: starting at 0 would swap every pair twice and put it back, and cells on the diagonal stay where they are.
function rotate(matrix) { const n = matrix.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { const t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } for (const row of matrix) row.reverse();}The trap
This version flips over the diagonal correctly, then reverses the order of the rows instead of each row. That is also a quarter turn, so the output looks plausible, but it turns the picture counterclockwise. Only a matrix that looks the same after a half turn, such as a single cell, comes out right.
function rotate(matrix) { const n = matrix.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { const t = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = t; } } matrix.reverse(); // reverses the order of the rows: that turns it counterclockwise}