Rotate a Square Matrix 90 Degrees Clockwise

Implement rotateMatrix

Given a square matrix, rotate it 90 degrees clockwise, in place: the element at matrix[i][j] moves to result[j][n-1-i]. Building a brand new matrix and placing each element at its rotated destination works, but it costs a full second matrix's worth of memory. A 90° clockwise rotation can be decomposed into two simpler, in-place operations: a transposeTransposeFlipping a matrix across its main diagonal — matrix[i][j] and matrix[j][i] swap places. (flip across the main diagonal), followed by reversing every row (a horizontal flip). Composing those two flips is exactly the same as rotating 90° clockwise — no extra matrix required.

Example 1:

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

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

Example 2:

Input: matrix = [[1,2],[3,4]]

Output: [[3,1],[4,2]]

Example 3:

Input: matrix = [[5]]

Output: [[5]]

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ n ≤ 20
  • -1000 ≤ matrix[i][j] ≤ 1000
  • matrix is a square matrix (n × n)

matrix =

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