Categories
interview

Rotate Matrix

To perform in place rotation of a matrix, the matrix needs to be a square matrix (n x n i.e., n-rows and n-columns). This case is similar to a square image rotation. The Javascript (ES6) code to rotate a square matrix 90° in clockwise direction is as follows:

const rotateMatrix = inp => {
  let n = inp.length;
  for (let layer = 0; layer < Math.floor(n / 2); layer++) {
    for (let start = layer; start < n - layer - 1; start++) {
      let temp = inp[layer][start];
      inp[layer][start] = inp[n - start - 1][layer];
      inp[n - start - 1][layer] = inp[n - layer - 1][n - start - 1];
      inp[n - layer - 1][n - start - 1] = inp[start][n - layer - 1];
      inp[start][n - layer - 1] = temp;
    }
  }
};

const matrix = [
  [3, 4, 5],
  [2, 0, 6],
  [1, 8, 7]
];
rotateMatrix(matrix);
console.log(matrix);
/*
  [
    [1, 2, 3],
    [8, 0, 4],
    [7, 6, 5]
  ]
*/

Demo