Top Interview 150
The Rotate Image problem involves rotating an nΓn matrix by 90 degrees clockwise, in place. Letβs solve LeetCode 48: Rotate Image step by step.
π Problem Description
Given an nΓn
matrix:
- Rotate the matrix in place by 90 degrees clockwise.
- In-place means modifying the original matrix without allocating extra space for another matrix.
π‘ Examples
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Input: matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]
Output: [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
Constraints
- 1β€m,nβ€10
- β100β€matrix[i][j]β€100
π JavaScript Solution
We solve this problem in two steps:
-
Transpose the Matrix:
- Swap elements symmetrically across the diagonal.
-
Reverse Each Row:
- Reverse the order of elements in each row to achieve the rotation.
Implementation
var rotate = function(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
};
π How It Works
- Transpose the Matrix:
- Swap
matrix[i][j]
withmatrix[j][i]
for alli<j
. - This converts rows into columns.
- Swap
Example:
Input: [[1, 2, 3], Transposed: [[1, 4, 7],
[4, 5, 6], -> [2, 5, 8],
[7, 8, 9]] [3, 6, 9]]
- Reverse Each Row:
- Reverse the elements of each row to achieve the clockwise rotation.
Example:
Transposed: [[1, 4, 7], Rotated: [[7, 4, 1],
[2, 5, 8], -> [8, 5, 2],
[3, 6, 9]] [9, 6, 3]]
π Complexity Analysis
-
Time Complexity:
- Transposing the matrix takes
O(n^2)
. - Reversing each row takes
O(n^2)
. - Total:
O(n^2)
- Transposing the matrix takes
Space Complexity:
O(1)
, as the rotation is done in place.
π Dry Run
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
β¨ Pro Tips for Interviews
-
Clarify Constraints:
- Ensure the matrix is always square (nΓn).
-
Highlight In-Place Operations:
- Emphasize the efficiency of the transpose-and-reverse method.
-
Edge Cases:
- Single-element matrix:
[[1]]
. -
2Γ2 matrix:
[[1, 2], [3, 4]]
.
- Single-element matrix:
π Learn More
Check out the full explanation and code walkthrough on my previous Dev.to post:
π Spiral Matrix - JavaScript Solution
Whatβs your preferred method to solve this problem? Letβs discuss! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!