Medium

Rotate Image

Description

Rotate a square matrix 90 degrees clockwise in place.

Solution

def rotate(matrix):
    for r in range(len(matrix)):
        for c in range(r+1,len(matrix)):
            matrix[r][c],matrix[c][r] = matrix[c][r],matrix[r][c]
    for row in matrix:
        row.reverse()

Examples

Inputs are positional arguments. Trees use level-order arrays; linked lists use value arrays. Design problems list operations in order.

Example 1

Input
[[[1,2],[3,4]]]
Output
[[3,1],[4,2]]

Each original column becomes a reversed output row.

Example 2

Input
[[[7]]]
Output
[[7]]

A one-cell matrix stays unchanged.

Example 3

Input
[[[1,2,3],[4,5,6],[7,8,9]]]
Output
[[7,4,1],[8,5,2],[9,6,3]]

The left column becomes the top row in reverse order.

Approach

Transpose across the main diagonal, then reverse each row.

Time & space

O(n²) time; O(1) auxiliary space for an n by n matrix.