Program to rotate square matrix by 90 degrees counterclockwise in Python

Rotating a square matrix 90 degrees counterclockwise is a common matrix transformation problem. We can achieve this using a two-step approach: first reverse each row, then transpose the matrix.

Understanding the Rotation

Let's visualize how a 90-degree counterclockwise rotation works:

Original Matrix 1 4 7 2 5 8 3 6 9 90° CCW After Rotation 7 8 9 4 5 6 1 2 3

Algorithm Steps

To rotate a matrix 90 degrees counterclockwise:

  • Reverse each row of the matrix

  • Transpose the matrix (swap elements across the main diagonal)

Implementation

class Solution:
    def rotate_counterclockwise(self, matrix):
        if not matrix or not matrix[0]:
            return []
        
        n = len(matrix)
        
        # Step 1: Reverse each row
        for row in matrix:
            row.reverse()
        
        # Step 2: Transpose the matrix
        for i in range(n):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        
        return matrix

# Test the solution
solution = Solution()
matrix = [
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]
]

print("Original matrix:")
for row in matrix:
    print(row)

result = solution.rotate_counterclockwise(matrix)
print("\nAfter 90° counterclockwise rotation:")
for row in result:
    print(row)
Original matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

After 90° counterclockwise rotation:
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]

Alternative Approach Using List Comprehension

For a more Pythonic solution, you can use list comprehension ?

def rotate_counterclockwise_alt(matrix):
    if not matrix or not matrix[0]:
        return []
    
    n = len(matrix)
    # Create new rotated matrix
    rotated = [[matrix[j][n-1-i] for j in range(n)] for i in range(n)]
    return rotated

# Test the alternative approach
matrix = [
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]
]

result = rotate_counterclockwise_alt(matrix)
print("Rotated matrix (list comprehension):")
for row in result:
    print(row)
Rotated matrix (list comprehension):
[7, 8, 9]
[4, 5, 6]
[1, 2, 3]

Comparison

Method Space Complexity Modifies Original Best For
In-place (reverse + transpose) O(1) Yes Memory efficiency
List comprehension O(n²) No Functional programming style

Conclusion

The in-place approach using row reversal and matrix transposition is memory-efficient with O(1) space complexity. Use the list comprehension method when you need to preserve the original matrix and prefer a more readable, functional approach.

Updated on: 2026-03-25T11:36:39+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements