Matrix Rotation in JavaScript

How to rotate a 2x2 matrix in javascript

Velu S Gautam1 min readInterviews

Rotating a matrix clockwise using for loops.

This question was asked in the live coding round of frontend developer interviews at Flipkart and Walmartlabs.

TYPESCRIPT
function rotateMatrixClockwise(matrix: string[]): string[] {
  if (!Array.isArray(matrix) || matrix.length === 0) {
    return [];
  }

  const rows = matrix.length;
  const cols = matrix[0].length;

  const isRectangular = matrix.every(row => row.length === cols);
  if (!isRectangular) {
    return [];
  }

  const result: string[] = Array(cols).fill('');

  for (let col = 0; col < cols; col++) {
    for (let row = rows - 1; row >= 0; row--) {
      result[col] += matrix[row][col];
    }
  }

  return result;
}

console.log(rotateMatrixClockwise(["a", "b", "c", "d"])); // "dcba"

Overall Time Complexity

  • General case: O(n × m)
  • Single-column case: O(n × 1)
  • Since the function handles both cases, the worst-case time complexity is O(n × m), where n is the number of rows and m is the number of columns.

Comments