AAlgoLoopSpaced repetition for LeetCode
EASYMatrix / GridLeetCode ↗

Transpose Matrix

The key idea

The transpose flips the matrix over its main diagonal: the value at row i, column j moves to row j, column i. A matrix with m rows and n columns becomes one with n rows and m columns, so allocate the result with swapped dimensions before copying.

Problem

Given a 2-D 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. In other words, the value at row i, column j of the input becomes the value at row j, column i of the result.

If the input has m rows and n columns, the transpose has n rows and m columns.

Constraints

Examples

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

Complexity

Time: O(m*n) Space: O(m*n)

See the full solution

410310
Step-by-step visualization
Start free →

More Matrix / Grid problems