01 · Question
Given a square n x n matrix, return a new matrix that results from:
- Transposing the matrix:
matrix[i][j]becomesmatrix[j][i]. - 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:
- Transpose the matrix (swap
matrix[i][j]withmatrix[j][i]). - Reverse each row.