Problem · Array

Rotate Image

Learn this problem
MediumTokopedia logoTokopediaFULLTIMEPHONE SCREEN

Problem statement

You are given an n × n integer matrix representing an image. Rotate the image by 90 degrees clockwise.

Perform the rotation in place by modifying matrix directly. Return that same matrix after the mutation so the runner can compare its final values; do not allocate another n × n matrix in the final approach.

Function

rotateImage(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 former bottom-left element becomes the new top-left element, and every position moves through one clockwise quarter-turn.

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]]

Each original column becomes a row in reverse vertical order.

Constraints

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

More Tokopedia problems

drafts saved locally
public int[][] rotateImage(int[][] matrix) {
    // Rotate matrix in place, then return it.
}
matrix[[1,2,3],[4,5,6],[7,8,9]]
expected[[7,4,1],[8,5,2],[9,6,3]]
checking account