Contact
Back to Home

Your challenge is to turn a square matrix in a clockwise manner while keeping it in place. Avoid creating any additional matrix.

Featured Answer

Question Analysis

The question is asking you to perform an in-place rotation of a square matrix by 90 degrees in a clockwise direction. An in-place operation means that you should modify the existing matrix without using any additional matrix or significant additional space. This type of problem is common in system design interviews as it tests your understanding of data manipulation and space efficiency, as well as your ability to work with complex data structures like matrices.

Answer

To rotate a square matrix in-place in a clockwise manner, you can follow these steps:

  1. Transpose the Matrix: Convert rows of the matrix into columns. This means swapping the elements at indices (i, j) with (j, i) for all i < j.

  2. Reverse Each Row: After transposing, reverse each row of the matrix. This will complete the rotation.

Here's a step-by-step explanation:

  • Step 1: Transpose the Matrix

    • Iterate over the matrix with two nested loops.
    • For each pair of indices (i, j), swap the elements at positions (i, j) and (j, i) if i < j.
    • This operation flips the matrix over its diagonal.
  • Step 2: Reverse Each Row

    • For each row in the matrix, reverse the row.
    • This operation aligns the transposed matrix to give the final rotated matrix.

Code Implementation:

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 i in range(n):
        matrix[i].reverse()

# Example usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
rotate_matrix(matrix)
# The matrix should now be:
# [
#     [7, 4, 1],
#     [8, 5, 2],
#     [9, 6, 3]
# ]

Key Points:

  • This solution runs in O(n^2) time complexity, where n is the dimension of the matrix, which is optimal for this problem.
  • It uses O(1) additional space since it modifies the matrix in place without allocating extra space for another matrix.