Blind 75
68 / 75Free practice

Rotate Image

Medium · Matrices

Jump to code

Rotate a square matrix 90 degrees clockwise in place. Do not allocate another matrix.

Examples

Example 1

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

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

Example 2

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

Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Constraints

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

Function contract

Modify matrix in place. The grader checks its value after your function returns.

Need a hint?

Two simple reflections compose a rotation.

Asked in real interviews

Candidates reported versions of Rotate Image from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      2,
      3
    ],
    [
      4,
      5,
      6
    ],
    [
      7,
      8,
      9
    ]
  ]
]
Expected
[
  [
    7,
    4,
    1
  ],
  [
    8,
    5,
    2
  ],
  [
    9,
    6,
    3
  ]
]
Case 2
Input
[
  [
    [
      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 3
Input
[
  [
    [
      1
    ]
  ]
]
Expected
[
  [
    1
  ]
]
Case 4
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ]
]
Expected
[
  [
    3,
    1
  ],
  [
    4,
    2
  ]
]
Case 5
Input
[
  [
    [
      0,
      -1
    ],
    [
      2,
      3
    ]
  ]
]
Expected
[
  [
    2,
    0
  ],
  [
    3,
    -1
  ]
]

Drafts are saved per language in this browser when storage is available.