Recently, I came across a problem to rotate a 2 dimensional matrix 90 degrees clockwise using an extra space (i.e. using additional memory).

Let us understand clockwise rotation first and we will be doing anticlockwise rotation in no time!

Rotation of a 3x3 matrix 90 degrees clockwise looks something like this:

Basically, columns become rows and rows become columns. Considering that the source matrix has dimension of MxN. The destination matrix has a dimension of NxM. It may not be obvious here since we are taking a square matrix, but take a non-square matrix and see it for yourself.

One thing to note is that 1st row in the source matrix becomes the last column in the destination matrix, 2nd row becomes 2nd last column and so on… (i.e. rows are reversely transformed into columns).

#matrix-rotation #problem-solving #javascript

Matrix Rotation in JavaScript
3.90 GEEK