hectane logo

Matrix Rotation in JavaScript

How to rotate a 2x2 matrix in javascript

Matrix Rotation in JavaScript

Rotating a matrix in clock wise direction using for loops. 

This question was asked in live coding round of Frontend developer interviews in Flipkart, Walmartlabs

function rotateMatrix(matrix) {
  // Input validation
  if (!matrix || !Array.isArray(matrix) || matrix.length === 0) {
    return [];
  }
  const n = matrix.length;
  const m = matrix[0].length;
  if (!matrix.every(row => typeof row === 'string' && row.length === m)) {
    return []; // Ensure all rows are strings of the same length
  }

  if (m === 1) {
    return [matrix.reverse().join('')];
  }

  // Initialize result array
  const result = Array(m).fill('');
  
  // Concatenate characters column-wise in reverse row order
  for (let j = 0; j < m; j++) {
    for (let i = n - 1; i >= 0; i--) {
      result[j] += matrix[i][j];
    }
  }
  
  return result;
}

console.log(
  rotateMatrix([
    '.........',
    '.##......',
    '..###....',
    '...###...',
    '.....###.',
    '......###',
    '.....###.',
    '...###...',
    '..###....',
    '.##......',
    '.........',
  ])
);

console.log(rotateMatrix(["a","b","c","d"])) // ["dcba"]
Overall Time Complexity