Skip to main content

Rotate a Square Matrix

MediumMatrixArrays103 tests

You get a square matrix matrix with n rows and n columns.

Turn the matrix 90 degrees clockwise (to the right) and return the result.

After the turn, the first row of the old matrix becomes the last column of the new matrix, the second row becomes the second-to-last column, and so on. In other words, the value at row i, column j moves to row j, column n - 1 - i.

Note

  • The judge reads only the value your function returns. You may change matrix in place, but you must still return it at the end.
  • Try to do it in place, without a second n x n matrix.

Hint: first swap matrix[i][j] with matrix[j][i] for every i < j (this flips the matrix over its main diagonal). Then reverse every row.

Examples

Example 1

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

The first row 1, 2, 3 becomes the last column, read from top to bottom. The last row 7, 8, 9 becomes the first column.

Example 2

Input:
[[-4,10],[0,3]]
Output:
[[0,-4],[3,10]]

The top row -4, 10 becomes the right column. The bottom row 0, 3 becomes the left column.

Example 3

Input:
[[42]]
Output:
[[42]]

A 1 x 1 matrix looks the same after any turn.

Constraints

  • 1 <= n <= 6
  • matrix.length == matrix[i].length == n
  • -50 <= matrix[i][j] <= 50

Run checks your code against the 3 examples. Submit checks it against all 103 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.