How to rotate a square matrix 90 degrees to the left in TypeScript

1 Answer

0 votes
function printMatrix(matrix: number[][]): void {
    matrix.forEach((row: number[]) => console.log(row.join(" ")));
}

/**
 * Rotates a square matrix 90 degrees to the left (counterclockwise).
 * @param matrix - The square matrix to rotate.
 */
function rotateMatrix90DegreesLeft(matrix: number[][]): void {
    const len: number = matrix.length;

    // Validate input: Ensure it's a square matrix
    if (
        !Array.isArray(matrix) ||
        !matrix.every((row: number[]) => Array.isArray(row) && row.length === len)
    ) {
        throw new Error("Input must be a square matrix.");
    }

    // Perform the rotation in-place
    for (let layer = 0; layer < Math.floor(len / 2); layer++) {
        const first = layer;
        const last = len - 1 - layer;

        for (let i = first; i < last; i++) {
            const offset = i - first;

            // Save the top element
            const top: number = matrix[first][i];

            // Move right to top
            matrix[first][i] = matrix[i][last];

            // Move bottom to right
            matrix[i][last] = matrix[last][last - offset];

            // Move left to bottom
            matrix[last][last - offset] = matrix[last - offset][first];

            // Move top to left
            matrix[last - offset][first] = top;
        }
    }
}

const matrix: number[][] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

rotateMatrix90DegreesLeft(matrix);

console.log("Matrix After 90° Left Rotation:");
printMatrix(matrix);



/*
run:

"Matrix After 90° Left Rotation:" 
"3 6 9" 
"2 5 8" 
"1 4 7" 

*/

 



answered Oct 6, 2025 by avibootz
...