Rotate an image 90°

Medium TimeO(n²) SpaceO(1)

Given an n × n matrix, turn it 90° clockwise in place, with no second matrix of the same size, so [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]]. The top row ends up as the right-hand column, and every value has to land where the rotation puts it rather than merely somewhere plausible.

Examples

Example 1

Input
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
[[7,4,1],[8,5,2],[9,6,3]]
The top row 1, 2, 3 is now the right-hand column, read downwards.

Example 2

Input
matrix = [[1, 2], [3, 4]]
Output
[[3,1],[4,2]]
The top row 1, 2 becomes the right-hand column, and an even size leaves no centre cell.

The Code

function rotate(matrix) {
  const n = matrix.length;
  for (let r = 0; r < n; r++) {
    for (let c = r + 1; c < n; c++) {
      const temp = matrix[r][c];
      matrix[r][c] = matrix[c][r];
      matrix[c][r] = temp;
    }
  }
  for (let r = 0; r < n; r++) {
    matrix[r].reverse();
  }
  return matrix;
}
rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
Done
Step through rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) call by call