How to use Optimal Approach (reduce Time Complexity) In Javascript
In this approach we will reduce time complexity of problem from O(N*N) to O(1). If we observe the matrix , we can rotate it by 90 degree clockwise by two simple steps. First we will take transpose of matrix (change rows to columns and rows to columns) and then reverse each row of matrix. The matrix obtained is rotated matrix (by 90 degrees).
Example : To demonstrate rotation of image by 90 degree in clockwise direction by taking transpose of matrix and reversing its each row.
function rotateBy90Degree(matrix) {
const n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < i; j++) {
[matrix[i][j],
matrix[j][i]] = [matrix[j][i],
matrix[i][j]];
}
}
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
}
function main() {
let arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
rotateBy90Degree(arr);
console.log("Rotated Image by 90 degree in clockwise direction ");
for (let i = 0; i < arr.length; i++) {
console.log(arr[i].join(" "));
}
}
main();
Output
Rotated Image by 90 degree in clockwise direction 7 4 1 8 5 2 9 6 3
Time Complexity: O(N*N) , transposing the matrix + O(N*N) , reversing rows = O(N*N)
Space Complexity: O(1), constant space
Rotate Image by 90 Degree using JavaScript
In this article, we are going to learn how we can rotate images by 90 degrees clockwise using JavaScript. In simple words, we are given a matrix, and we have to rotate it by 90 degrees clockwise. To understand the question clearly, below is the image illustration explaining how the matrix looks when it is rotated 90 degrees clockwise:
Table of Content
- Brute force Approach
- Using Optimal Approach (reduce Time Complexity)