AceYourInterviews
Checking sign-in…

11. Rotate Image

IntermediateCoordinate composition and in-place swaps

Imagine turning the entire square image one quarter-turn to the right. Move each cell to its new position in the original matrix, rather than allocating a separate rotated image.

This is a rotation, not a transpose or a reflection. Preserve both the outer matrix object and its row objects as required by the contract.

Example 1

Input

[[1,2],[3,4]]

Output

[[3,1],[4,2]]

Explanation: The first column becomes the first output row in bottom-to-top order.

Example 2

Input

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

Output

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

Explanation: The center stays fixed while corner and edge occurrences move.

Constraints

  • 0 <= n <= 300
  • matrix.length == matrix[r].length == n
  • -231 <= matrix[r][c] <= 231 - 1
  • Rows are distinct arrays. Rotate the values in place.
Hints
Hint 1

Write the destination coordinate of an arbitrary original cell.

Hint 2

Which two reflections compose to that mapping?

Hint 3

Transpose once across the main diagonal, then reverse every row.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Transpose, then reverse rows

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