Rotate Matrix, Advanced

Learn how to rotate a matrix in place. We'll go over the complex algorithm required in heavy detail.

Rotate Square Matrix in Place

147258369

⬇️

789456123

Instructions

Write a function that takes a square matrix as input. A square matrix has the same number of rows and columns, e.g. 3 x 3, 4 x 4, 5 x 5. It should return the same matrix rotated 90 degrees clockwise. The rotation should happen in place, meaning you may not create any extra matrixes or arrays in your function.

Input: Array of arrays of numbers

Output: Array of arrays of numbers

Example

An input of:

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

yields an output of:

[[7, 4, 1],
 [8, 5, 2],
 [9, 6, 3]]

Hints

  1. Start at the border and work your way in.
  2. We’ll need some placeholder variables.

Press + to interact
function rotateClockwise(mat) {
// Your code here
}

Solution

Press + to interact
function rotateClockwise(mat) {
const totalLayers = Math.floor(mat.length / 2);
for(let layer = 0; layer < totalLayers; layer++) {
const lastIndex = mat.length - 1 - layer;
for(let forwardIterator = layer + 1; forwardIterator < mat.length - layer; forwardIterator++) {
const reverseIterator = lastIndex - forwardIterator + layer;
let temp1 = mat[forwardIterator][lastIndex];
mat[forwardIterator][lastIndex] = mat[layer][forwardIterator];
let temp2 = mat[lastIndex][reverseIterator];
mat[lastIndex][reverseIterator] = temp1;
temp1 = mat[reverseIterator][layer];
mat[reverseIterator][layer] = temp2;
mat[layer][forwardIterator] = temp1;
}
}
return mat;
}
...

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.