# Rotate Image

2 min readApr 26, 2021

leetcode 48

You are given an *n* x *n* 2D `matrix`

representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image **in place**, which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.

To solve the question we can first reverse the matrix, which will give us the following:

`matrix.reverse()`

After we reverse the matrix, we can see that we still need to exchange 4 with 8, 9 with 1, 6 with 2. We can do that by looping through the matrix to exchange the element:

`for(let i=0;i<matrix.length;i++){`

for(let j=i;j<matrix[i].length;j++){

let temp = matrix[i][j]

matrix[i][j] = matrix[j][i]

matrix[j][i] = temp

}

}

This will get us:

And, that’s it!

The final result:

`var rotate = function(matrix) {`

matrix.reverse()

for(let i=0;i<matrix.length;i++){

for(let j=i;j<matrix[i].length;j++){

let temp = matrix[i][j]

matrix[i][j] = matrix[j][i]

matrix[j][i] = temp

}

}

};

Give me some likes if you like the solution, let me know how you think.