Transpose Matrix
LeetCode 898 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Constraints:
- `m == matrix.length`
- `n == matrix[i].length`
- `1 <= m, n <= 1000`
- `1 <= m * n <= 10^5`
- `-10^9 <= matrix[i][j] <= 10^9`
Topics: Array, Matrix, Simulation
Approachβ
Matrixβ
Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.
When to use
Grid traversal, island problems, path finding, rotating/transforming matrices.
Solutionsβ
Solution 1: C# (Best: 320 ms)β
| Metric | Value |
|---|---|
| Runtime | 320 ms |
| Memory | N/A |
| Date | 2018-07-11 |
Solution
public class Solution {
public int[][] Transpose(int[][] A) {
int m = A.GetLength(0);
int n = A[0].GetLength(0);
int[][] result = new int[n][];
for (int i = 0; i < n; i++)
{
result[i] = new int[m];
}
for (int j = 0; j < n; j++){
for (int i = 0; i < m; i++)
{
result[j][i] = A[i][j];
}
Console.WriteLine();
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 1 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!