Approach: The optimal in-place solution consists of two steps:
1. Transpose the matrix by swapping elements across its main diagonal. This converts rows into columns. 2. Reverse each row of the transposed matrix to achieve a 90-degree clockwise rotation.
This approach avoids using extra memory for another matrix and modifies the original matrix directly, making it suitable for large inputs and interview scenarios.
Java Solution:
public class RotateImage {
public static void rotate(int[][] matrix) {
int size = matrix.length;
// Step 1: Transpose the matrix
for (int row = 0; row < size; row++) {
for (int column = row + 1; column < size; column++) {
int temp = matrix[row][column];
matrix[row][column] = matrix[column][row];
matrix[column][row] = temp;
}
}
// Step 2: Reverse each row
for (int row = 0; row < size; row++) {
int left = 0;
int right = size - 1;
while (left < right) {
int temp = matrix[row][left];
matrix[row][left] = matrix[row][right];
matrix[row][right] = temp;
left++;
right--;
}
}
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
rotate(matrix);
printMatrix(matrix);
}
}Output: 7 4 1 8 5 2 9 6 3
Time Complexity: O(n²), where n is the dimension of the matrix. Every element is visited a constant number of times during transpose and reversal operations.
Space Complexity: O(1), since the rotation is performed in-place without allocating another matrix.
Key Interview Points: • The transpose-and-reverse technique is the standard optimal solution for in-place matrix rotation. • Using an additional matrix would simplify implementation but increase space complexity to O(n²). • A common interview follow-up is to rotate the matrix by 90 degrees anti-clockwise or by 180 degrees.