Difficulty: Medium, Asked-in: Google, Facebook, Microsoft, Amazon, Morgan Stanley
Key takeaway: This is a well-known matrix problem that can be solved in-place using loops and matrix properties.
Given an n x n square matrix, write a program to rotate the matrix by 90 degrees in the anti-clockwise direction. The goal is to perform the matrix rotation in place, meaning we need to rotate the matrix without using extra space.
Important note: Before moving on to solutions, we recommend trying this problem on paper for atleast 15 or 30 minutes. Enjoy problem-solving!
If we observe the input and output matrices, the following pattern would be visible: The first row has turned into the first column in reverse order. Similarly, the second, third, … and last rows have turned into their respective columns in reverse order. For example:
So one basic idea would be to use an extra matrix of the same size and directly copy elements from the original matrix based on the above observation.
int[][] rotateMatrix(int X[][], int n)
{
int temp[n][n]
for (int i = 0; i < n; i = i + 1)
{
for (int j = 0; j < n; j = j + 1)
{
temp[n - j - 1][i] = X[i][j]
}
}
return temp
}
In the above approach, we are traversing the input matrix using two nested loops, which take O(n²) time. So the time complexity is O(n²). We are using an extra matrix of size n x n, so the space complexity is O(n²).
As given in the problem description, can we solve the problem without using extra space or in-place? Can we observe some pattern in the anticlockwise rotation of the matrix? Let's think!
If we deep dive into the input and output, we can find patterns to rotate the matrix by swapping values. Let’s go through the same observation from the above approach.
After the rotation of a matrix by 90 degrees anticlockwise:
So if we take the transpose of the input matrix:
So one solution idea would be: If we take the transpose of the input matrix and reverse each column, we will get the desired matrix rotated by 90 degrees in an anticlockwise direction (Think!).
Convert given matrix into its transpose: The transpose of a matrix is obtained by flipping the matrix over its diagonal, i.e., the row index of an element becomes the column index and vice versa. So we need to swap the elements at position X[i][j] with the element at X[j][i].
for (int i = 0; i < n; i = i + 1)
{
for (int j = i; j < n; j = j + 1)
{
swap(X[i][j], X[j][i])
}
}
Reverse transposed matrix column-wise: We run two nested loops where the outer loop iterates over each column from 0 to n - 1, and the inner loop reverses each column by swapping values.
int i = 0, j = 0, column = 0
while (column < n)
{
i = 0, j = n - 1
while (i < j)
{
swap(X[i][column], X[j][column])
i = i + 1
j = j - 1
}
column = column + 1
}
void rotateMatrix(int X[][], int n)
{
if(n == 0 || n == 1)
return
for (int i = 0; i < n; i = i + 1)
{
for (int j = i; j < n; j = j + 1)
{
swap(X[j][i], X[i][j])
}
}
int i = 0, j = 0, column = 0
while (column < n)
{
i = 0, j = n - 1
while (i < j)
{
swap(X[i][column], X[j][column])
i = i + 1
j = j - 1
}
column = column + 1
}
}
def rotateMatrix(X, n):
if n == 0 or n == 1:
return
for i in range(n):
for j in range(i, n):
X[j][i], X[i][j] = X[i][j], X[j][i]
column = 0
while column < n:
i, j = 0, n - 1
while i < j:
X[i][column], X[j][column] = X[j][column], X[i][column]
i = i + 1
j = j - 1
column = column + 1
We traverse the input matrix twice using nested loops. The time complexity is the sum of the time complexity of converting the input matrix into a transpose and reversing the transposed matrix column-wise, which is O(n²) + O(n²) = O(n²). The space complexity is O(1) since no extra memory is required.
There is another approach that can solve this problem in place. By tracking the initial and final positions of each element after rotation, we can derive a solution pattern.
So here are critical observations from the above image:
Observation 1: There are a total of n/2 squares in an n x n matrix. So, we can process each square one at a time using a nested loop. We first process the first square formed by the first row, last column, last row, and first column. Then we process the second square formed by the second row, second-last column, second-last row, and second column. And so on, moving from the outer square to the innermost square.
Observation 2: In each square, elements are moved in a cycle of 4 elements. So we need to swap elements involved in each cycle in the anticlockwise direction, i.e., from right to top, top to left, left to bottom, and bottom to the right. In general, the position of elements in any cycle is: (i, j), (n - 1 - j, i), (n - 1 - i, n - 1 - j), and (j, n - 1 - i). So we exchange the positions of all such pairs of four elements to rotate the matrix by 90 degrees in the anticlockwise order.
void rotateMatrix(int X[][], int n)
{
for (int i = 0; i < n / 2; i = i + 1)
{
for (int j = i; j < n - i - 1; j = j + 1)
{
int temp = X[i][j]
X[i][j] = X[j][n - 1 - i]
X[j][n - 1 - i] = X[n - 1 - i][n - 1 - j]
X[n - 1 - i][n - 1 - j] = X[n - 1 - j][i]
X[n - 1 - j][i] = temp
}
}
}
def rotateMatrix(X, n):
for i in range(n // 2):
for j in range(i, n - i - 1):
temp = X[i][j]
X[i][j] = X[j][n - 1 - i]
X[j][n - 1 - i] = X[n - 1 - i][n - 1 - j]
X[n - 1 - i][n - 1 - j] = X[n - 1 - j][i]
X[n - 1 - j][i] = temp
We are traversing each element of the input matrix only once using a nested loop and fixing its correct position. The time complexity is O(n²), and the space complexity is O(1) since no extra memory is needed.
Here is a precise mathematical analysis of the above code. For i = 0, the inner loop runs n times; for i = 1, the inner loop runs n - 2 times; for i = 2, the inner loop runs n - 4 times, and so on! So the total number of loop iterations is n + (n - 2) + (n - 4) + .... + 1 = 1 + 3 + 5 + .... + n - 4 + n - 2 + n.
The general formula for the sum of an arithmetic series is n/2[2a + (n − 1) × d], where n is the total number of terms, a is the first term, and d is a common difference. So in the sequence 1, 3, 5, ... n - 2, n, the first term is 1, the total number of terms is n/2, and the common difference is 2.
If we put these values in the formula for the sum, the total number of loop iterations is 1 + 3 + 5 + .... + n - 4 + n - 2 + n = n/4 [2 + (n/2 − 1) × 2] = n/4 [2 + (n/2 − 1) × 2] = n/4 * n = (n/2)². At each iteration, we are doing O(1) operations. So the time complexity is Total number of loop iterations * O(1) = (n/2)² * O(1) = O(n²)
If you have any queries/doubts/feedback, please write us at contact@enjoyalgorithms.com. Enjoy learning, Enjoy algorithms!