Rotate Matrix by 90 Degrees Clockwise - Optimal Approach

Rotate Matrix by 90 Degrees Clockwise - Optimal Approach

Algorithm Steps

  1. Given an n x n square matrix.
  2. Step 1: Transpose the matrix: swap matrix[i][j] with matrix[j][i] for all i < j.
  3. Step 2: Reverse each row of the matrix.
  4. The matrix is now rotated 90 degrees clockwise.

Rotate a Matrix 90 Degrees Clockwise (In-place) Code

Python
JavaScript
Java
C++
C
def rotate_matrix(matrix):
    n = len(matrix)
    # Transpose the matrix
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    # Reverse each row
    for row in matrix:
        row.reverse()

    return matrix

# Sample Input
mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
rotated = rotate_matrix(mat)
for row in rotated:
    print(row)