Hone logo
Hone
Problems

Rotate Image

You are given an n x n 2D matrix representing an image. Your task is to rotate the image by 90 degrees clockwise. This operation is fundamental in image processing and computer graphics for various transformations and manipulations.

Problem Description

The goal is to rotate an n x n square matrix 90 degrees clockwise. This means that the element at row r and column c should move to a new position after the rotation. The rotation should be performed in-place, meaning you should modify the original matrix directly without creating a new one, unless absolutely necessary for intermediate steps.

Key Requirements:

  • Rotate the image 90 degrees clockwise.
  • Perform the rotation in-place if possible.
  • The input matrix will always be square (n x n).

Expected Behavior:

  • The element at matrix[r][c] will end up at matrix[c][n - 1 - r].

Edge Cases to Consider:

  • An empty matrix (n=0).
  • A 1x1 matrix.

Examples

Example 1:

Input:
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Output:
[
  [7, 4, 1],
  [8, 5, 2],
  [9, 6, 3]
]
Explanation:
The element 1 at (0,0) moves to (0,2).
The element 2 at (0,1) moves to (1,2).
The element 3 at (0,2) moves to (2,2).
The element 4 at (1,0) moves to (0,1).
... and so on.

Example 2:

Input:
[
  [ 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]
]
Explanation:
The element 5 at (0,0) moves to (0,3).
The element 1 at (0,1) moves to (1,3).
...and so on.

Example 3:

Input:
[
  [1]
]
Output:
[
  [1]
]
Explanation:
A 1x1 matrix remains unchanged after rotation.

Constraints

  • n will be between 0 and 200, inclusive.
  • The matrix will contain integers.
  • The elements in the matrix will be between -1000 and 1000, inclusive.
  • The time complexity should ideally be O(n^2).
  • The space complexity should ideally be O(1) (in-place modification).

Notes

Consider the transformation rule: matrix[r][c] moves to matrix[c][n - 1 - r]. You'll need to find a way to swap elements efficiently to achieve this transformation. Think about how you can rotate a single element and then generalize that to multiple elements, perhaps by rotating layers or groups of elements.

Loading editor...
plaintext