Matrix Operations (Rotate & In-place)

Given a square n x n matrix, return a new matrix that results from:

  1. Transposing the matrix: matrix[i][j] becomes matrix[j][i].
  2. Rotating the matrix 90 degrees clockwise.

Example:

  • Input:

    [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
    
  • Transpose Output:

    [[1, 4, 7],
     [2, 5, 8],
     [3, 6, 9]]
    
  • Rotate 90° Output:

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

In-place Rotation (Common Follow-up): To rotate the matrix in-place (without allocating a new n x n matrix), you can perform two steps:

  1. Transpose the matrix (swap matrix[i][j] with matrix[j][i]).
  2. Reverse each row.
1def transpose(matrix: List[List[int]]) -> List[List[int]]:
2 n = len(matrix)
3 res = [[0] * n for _ in range(n)]
4 for r in range(n):
5 for c in range(n):
6 res[c][r] = matrix[r][c]
7 return res
8
9def rotate(matrix: List[List[int]]) -> List[List[int]]:
10 n = len(matrix)
11 res = [[0] * n for _ in range(n)]
12 for r in range(n):
13 for c in range(n):
14 res[c][n - 1 - r] = matrix[r][c]
15 return res
16
17def rotate_in_place(matrix: List[List[int]]) -> None:
18 n = len(matrix)
19 # 1. Transpose
20 for r in range(n):
21 for c in range(r + 1, n):
22 matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
23
24 # 2. Reverse Rows
25 for r in range(n):
26 matrix[r].reverse()
1
2
3
4
5
6
7
8
9
step=Start
Step 1 / 9
Step 1:
Start with the original matrix. We will perform In-place Rotation: Transpose then Reverse Rows.
Focus: default
step="Start"