To rotate a square matrix by 90 degrees clockwise without using extra space, we need to reposition the elements in-place. Instead of rotating each layer individually (which is another method), this optimal approach uses two simple steps:
Step 1: Transpose the Matrix
Transposing a matrix means converting rows into columns. We swap every element matrix[i][j]
with matrix[j][i]
for all i < j
. After this step, the matrix is flipped along its diagonal.
Step 2: Reverse Each Row
Now, we reverse each row in the transposed matrix. This aligns all the elements to their new 90-degree rotated positions.
Why This Works
When we transpose the matrix, the top row becomes the left column. But to fully rotate it clockwise, we still need to move the last column to the top, which is achieved by reversing each row after transposition.
Let’s Discuss Different Scenarios
- Normal Square Matrix: For matrices like 2x2, 3x3, or 4x4, the algorithm works seamlessly and efficiently, with no extra space used.
- Matrix with One Element: Rotating a 1x1 matrix has no visible effect. The matrix stays the same.
- Empty Matrix: There's nothing to rotate. The function should simply return an empty list or matrix.
- Non-Square Matrix: This approach only works on square matrices (equal number of rows and columns). If the matrix is not square, this logic should not be applied as it would produce incorrect results.
Because we don’t use any extra space, this is an in-place O(1) space and O(n²) time solution, where n
is the number of rows (or columns).