FastPrepRotate a Square Matrix 90 Degrees

Rotate a Square Matrix 90 Degrees

Microsoft logoMicrosoft● MediumINTERNONSITE INTERVIEW

Updated

Problem statement

You are given an n x n integer matrix matrix. Rotate it by 90 degrees clockwise and return the result.

After the rotation, the value that was in row r and column c is in row c and column n - 1 - r. In other words, the first column, read from bottom to top, becomes the first row.

Try to rotate the matrix in place, using only a constant amount of extra memory, and then return matrix itself. The judge checks only the matrix you return, so returning a new rotated matrix is also accepted.

Function

rotateMatrix(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]]
matrix
012012314562789
return
012074118522963
Moved or new

The first column read from bottom to top, 7, 4, 1, becomes the first row. The middle column read from bottom to top, 8, 5, 2, becomes the second row, and the last column, 9, 6, 3, becomes the third row. The center value 5 stays where it is.

Example 2

matrix = [[-3,10],[0,7]]return = [[0,-3],[7,10]]
matrix
010-310107
return
0100-31710
Moved or new

Each corner moves one corner clockwise: top-left -3 goes to top-right, top-right 10 goes to bottom-right, bottom-right 7 goes to bottom-left, and bottom-left 0 goes to top-left.

Example 3

matrix = [[42]]return = [[42]]
matrix
0042
return
0042

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

Constraints

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

More Microsoft Onsite Interview questions

Similar questions at other companies

Interview reports that mention this question

Microsoft interview experiences

All Microsoft interview questionsSee Microsoft hiring insights
Saved
class Solution {
    public int[][] rotateMatrix(int[][] matrix) {
        // Write your code here.
    }
}
Checking account…