Skip to content

Instantly share code, notes, and snippets.

@riggedjs
Created December 11, 2021 19:59
Show Gist options
  • Save riggedjs/74d6ceb1ff69a4956fda93378c31305b to your computer and use it in GitHub Desktop.
Save riggedjs/74d6ceb1ff69a4956fda93378c31305b to your computer and use it in GitHub Desktop.
Rotate Matrix in JavaScript
// 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