48. Rotate Image

ArrayMathMatrix

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)

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;
            }
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.