Facebook PixelRotate Image — Coding Practice
Rotate ImageMedium

Rotate Image

Medium 17.2k73% acceptance
ArrayMatrixMath

You are given an n × n 2D matrix representing an image. Rotate the image 90 degrees clockwise.

Do the rotation in place — modify matrix directly without allocating another n × n grid — and return it.

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 becomes the right column.
Example 2
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Example 3
Input: matrix = [[5]]
Output: [[5]]
Constraints
  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 20
  • -1000 ≤ matrix[i][j] ≤ 1000
Asked atAmazonMicrosoftAppleGoogle
JavaScript
Loading editor…
Case 1
[[1,2,3],[4,5,6],[7,8,9]]
expected: [[7,4,1],[8,5,2],[9,6,3]]
Case 2
[[1,2],[3,4]]
expected: [[3,1],[4,2]]
Case 3
[[5]]
expected: [[5]]
Case 4
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
expected: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
Case 5
[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
expected: [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]]
Case 6
[[0,-1],[-2,-3]]
expected: [[-2,0],[-3,-1]]