Learn Code
Depth-First Search
Greedy Algorithms
Matrices
Rotate Image
medium
DESCRIPTION (credit Leetcode.com)
Write a function to rotate an n x n 2D matrix representing an image by 90 degrees clockwise. The rotation must be done in-place, meaning you should modify the input matrix directly without using an additional matrix for the operation.
Input:
Output:
Explanation: The matrix is rotated by 90 degrees clockwise, transforming its columns into rows in reverse order.
Explanation
Step 1:
n = 3
0 / 12
Step 2:
swap matrix[2][2] and matrix[2][2]
0 / 4
Solution
rotate image
0 / 17
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n²) where n
is the number of rows in the matrix. We need to process each element in the matrix.
Space Complexity: O(1) since we are doing the rotation in-place without using extra space.
Login to track your progress
Your account is free and you can post anonymously if you choose.