48. Rotate Image 🔄

Difficulty: Medium - Tags: Matrix, Simulation

LeetCode Problem Link


Problem Statement 📜

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise.

Constraints:

  • The rotation must be performed in-place, modifying the input 2D matrix directly.

  • Do not allocate another 2D matrix for the rotation.


Examples 🌟

🔹 Example 1:

Input:

Output:

🔹 Example 2:

Input:

Output:


Constraints ⚙️

  • n == matrix.length == matrix[i].length

  • 1 <= n <= 20

  • -1000 <= matrix[i][j] <= 1000


Solution 💡

To rotate the image by 90 degrees clockwise, we follow these steps:

  1. Transpose the Matrix:

    • Swap the elements matrix[i][j] with matrix[j][i] for all i < j.

  2. Reverse Each Row:

    • Reverse the order of elements in each row of the transposed matrix.

This in-place transformation achieves the required rotation.


Java Solution


Explanation of the Solution

  1. Transpose the Matrix:

    • Swap matrix[i][j] and matrix[j][i] to flip the rows and columns along the main diagonal.

  2. Reverse Each Row:

    • Use two pointers to swap the first and last elements of each row, moving inward.

  3. Result:

    • The combination of transposing and reversing each row results in a 90-degree clockwise rotation.


Time Complexity ⏳

  • O(n²):

    • Transposing the matrix takes O(n²).

    • Reversing the rows also takes O(n²).

Space Complexity 💾

  • O(1):

    • The rotation is performed in-place, so no extra memory is used.

You can find the full solution here.

Last updated

Was this helpful?