AlgoInsight

DSA problem

Transpose Matrix

EasyMatrix (2D Array)Pattern: Matrix Manipulationtop600AmazonGoogleMicrosoftAdobe

Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is obtained by flipping the matrix over its main diagonal, switching the matrix's row and column indices.

Concretely, if the original matrix has R rows and C columns, the transposed matrix has C rows and R columns, and the element at position (i, j) in the result equals the element at position (j, i) in the original. Unlike an in-place rotation, a transpose of a non-square matrix changes the overall shape, so a fresh result matrix of dimensions C x R is generally required.

The intuition for the optimal approach is direct simulation: allocate a result matrix sized C x R, then iterate over every cell (i, j) of the original and write its value into result[j][i]. This single pass touches each element exactly once, giving linear time in the number of cells. Because the transpose can have different dimensions than the input, building a new array is the cleanest and canonical solution.

Examples

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Explanation: Element at (0,1)=2 moves to (1,0); (0,2)=3 moves to (2,0); the main diagonal 1,5,9 stays fixed.
Example 2
Input: matrix = [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Explanation: The input is 2x3, so the transpose is 3x2. Row [1,2,3] becomes the first column [1,2,3] read downward.
Example 3
Input: matrix = [[5]]
Output: [[5]]
Explanation: A 1x1 matrix is its own transpose since there is only the single diagonal element.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

matrixarraysimulationtwo-dimensional

Browse all DSA problems