48/670

48. Rotate Image

Medium

You are given matrix, an n × n grid of integers representing an image. Turn the whole image 90 degrees clockwise, in place: mutate the grid you were handed rather than returning a fresh one (the function returns nothing, and the judge prints the grid after your call).

After the turn, the old top row reads down the new rightmost column, the old left column becomes the new top row, and in general the value at row i, column j lands at row j, column n − 1 − i.

An extra n × n buffer makes this easy — the real exercise is doing it with O(1) additional memory.

90° clockwise rotation of a 3×3 matrixThe highlighted top row [1, 2, 3] becomes the rightmost column, read top to bottom.
90° clockwise123456789741852963beforeafter

Example 1:

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

Output: [[7,4,1], [8,5,2], [9,6,3]] (matrix mutated in place)

Explanation: The top row 1 2 3 becomes the rightmost column read top to bottom; the left column 1 4 7 becomes the top row read right to left.

Example 2:

Input: matrix = [[1,2], [3,4]]

Output: [[3,1], [4,2]] (matrix mutated in place)

Explanation: Each corner shifts one position clockwise: 1→top-right, 2→bottom-right, 4→bottom-left, 3→top-left.

Constraints:

  • 1 ≤ n ≤ 20
  • -1000 ≤ matrix[i][j] ≤ 1000

Hints:

Write down where a single cell goes: (i, j) → (j, n−1−i). With a second n×n buffer you can place every value directly and copy the buffer back.

For the in-place version, look for two simple reflections that compose into a rotation. A clockwise quarter-turn equals a transpose followed by reversing each row.

Transposing means swapping matrix[i][j] with matrix[j][i] for j > i only — sweep the full square and you will swap everything back to where it started.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

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