Rotate Image

35 min · rotate()

Turn a square photo to the right, and its top row becomes its right column.

You're given an n x n integer matrix. Rotate it 90 degrees clockwise and return the rotated matrix.

Every input cell must appear once in the result. Rows become columns, and their order changes with the turn: the bottom-left value moves to the top-left, while the original top-left value moves to the top-right.

You may rearrange the input matrix itself. Either way, return the finished matrix so the result can be checked.

Constraints

  • 1 <= n <= 100
  • matrix has exactly n rows, and every row has exactly n values.
  • -1_000 <= matrix[i][j] <= 1_000

Hints

Write the destination coordinates

A value at row i, column j lands at row j, column n - 1 - i. A fresh matrix makes that rule direct to implement.

Split the turn into two mirrors

First swap values across the main diagonal, turning rows into columns. Then reverse every row. Try those two moves on a 3×3 grid by hand.

Swap only once

During the diagonal swap, visit only cells above the diagonal (j > i). Visiting both halves would swap each pair twice and undo the work.

Follow-up

Can you perform the rotation with O(1) extra working space?

Visible cases

Examples

Example 1

ready
Input
matrix = [
  [
    1,
    2,
    3
  ],
  [
    4,
    5,
    6
  ],
  [
    7,
    8,
    9
  ]
]
Expected
[
  [
    7,
    4,
    1
  ],
  [
    8,
    5,
    2
  ],
  [
    9,
    6,
    3
  ]
]
Why
the bottom row becomes the left-to-right first column after a clockwise turn

Example 2

ready
Input
matrix = [
  [
    1
  ]
]
Expected
[
  [
    1
  ]
]
Why
a one-cell image is unchanged by rotation

Example 3

ready
Input
matrix = [
  [
    1,
    2
  ],
  [
    3,
    4
  ]
]
Expected
[
  [
    3,
    1
  ],
  [
    4,
    2
  ]
]
Why
each corner advances one corner clockwise

Interview signal

Asked at

AmazonMicrosoftApple
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite