Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
🧠 Why Learn This?
Matrix rotation isn't just a coding interview favorite It's used in AI, ML, and image processing to manipulate data efficiently.
Think:
Rotate Image
Want to rotate a 2D matrix 90° clockwise in-place without using extra space?
Original Matrix:
Rotated Matrix:
One way to solve it is:
What is Transposing a Matrix?
Final Transposed Matrix:
Step 2: Reverse Each Row
Final Reversed Matrix:
var rotate = function(matrix) { const n = matrix.length;// Step 1: Transpose the matrix for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { // Swap matrix[i][j] with matrix[j][i] [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; } }// Step 2: Reverse each row for (let i = 0; i < n; i++) { matrix[i].reverse(); } };By first transposing the matrix (swap rows and columns) and then reversing each row, we get a clean 90° clockwise rotation — all done in-place with O(1) space.
Simple, elegant, and powerful.