LeetCode 48: Rotate Image Solution

Master LeetCode problem 48 (Rotate Image), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

48. Rotate Image

Problem Explanation

Explanation

To rotate the image by 90 degrees clockwise in-place, we can perform the rotation in layers starting from the outermost layer and moving towards the center. At each layer, we swap the elements in groups of four, rotating each element to its corresponding position in the 90-degree rotated image.

  1. We iterate through each layer starting from the outermost layer.
  2. For each layer, we iterate through the elements in that layer from left to right.
  3. For each element, we perform four swaps to rotate the elements in that layer.

Time complexity: O(n^2)
Space complexity: O(1)

Solution Code

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        
        for (int layer = 0; layer < n / 2; layer++) {
            int first = layer;
            int last = n - 1 - layer;
            
            for (int i = first; i < last; i++) {
                int offset = i - first;
                
                int top = matrix[first][i];
                
                matrix[first][i] = matrix[last - offset][first];
                matrix[last - offset][first] = matrix[last][last - offset];
                matrix[last][last - offset] = matrix[i][last];
                matrix[i][last] = top;
            }
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 48 (Rotate Image)?

This page provides optimized solutions for LeetCode problem 48 (Rotate Image) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 48 (Rotate Image)?

The time complexity for LeetCode 48 (Rotate Image) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 48 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 48 in Java, C++, or Python.

Back to LeetCode Solutions