FastPrepRotate a Square Matrix Clockwise

Rotate a Square Matrix Clockwise

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

Given an n x n integer matrix, rotate it exactly 90 degrees clockwise in place.

Do not allocate another n x n matrix. Return the same matrix after the rotation so the result can be checked.

Function

rotateMatrixClockwise(matrix: int[][]) → int[][]

Examples

Example 1

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

The left column becomes the top row, and every other value moves to its clockwise position.

Example 2

matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]return = [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Both square layers rotate clockwise.

Example 3

matrix = [[5]]return = [[5]]

A one-cell matrix is unchanged.

Constraints

  • 1 <= n <= 200.
  • matrix.length == n and every row has length n.
  • -10^9 <= matrix[row][col] <= 10^9.

More Google problems

See Google hiring insights
public int[][] rotateMatrixClockwise(int[][] matrix) {
  // Write your code here.
}
matrix[[1,2,3],[4,5,6],[7,8,9]]
expected[[7,4,1],[8,5,2],[9,6,3]]
Checking account…