Created
December 11, 2021 19:59
-
-
Save riggedjs/74d6ceb1ff69a4956fda93378c31305b to your computer and use it in GitHub Desktop.
Rotate Matrix in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// time and space complexity of O(n2) and O(1) respectively | |
const rotateImage = (matrix) => { | |
if (!matrix.length || !matrix[0].length) return []; | |
const len = matrix.length; | |
// transpose matrix | |
for (let i = 0; i < len; i++) { | |
for (let j = i; j < len; j++) { | |
const curr = matrix[i][j]; | |
matrix[i][j] = matrix[j][i]; | |
matrix[j][i] = curr; | |
} | |
} | |
const middle = Math.floor(len / 2); | |
// swap left-most value with right-most value until middle is reached | |
for (let i = 0; i < len; i++) { | |
for (let j = 0; j < middle; j++) { | |
const curr = matrix[i][j]; | |
const endPos = len - 1 - j; | |
matrix[i][j] = matrix[i][endPos]; | |
matrix[i][endPos] = curr; | |
} | |
} | |
return matrix; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment