Skip to main content
Back to problems
Leetcode
Easy
Arrays
Matrices
Transpose Matrix

Return the transpose of a matrix by swapping its rows and columns.

Acceptance 0%
Problem Statement

Transpose Matrix

Given a 2D matrix matrix, return its transpose.

The transpose of a matrix is formed by turning rows into columns. If matrix has m rows and n columns, the result should have n rows and m columns, where the element at position [i][j] in the input appears at position [j][i] in the output.

Input Format

  • A 2D integer matrix matrix with m rows and n columns.

Output Format

  • Return a new 2D matrix representing the transpose of matrix.

Constraints

  • 1 <= m, n
  • The matrix may be rectangular.
  • Elements should be preserved exactly; only their positions change.

Hints

  • Think about how to build the output dimensions before filling values.
  • The value at row r and column c in the input should go to row c and column r in the answer.

Input Format

A 2D integer matrix matrix with m rows and n columns.

Output Format

Return a 2D integer matrix of size n x m that is the transpose of the input.

Constraints

  • 1 <= m, n
  • The matrix can be rectangular.
  • Preserve all values exactly.
  • Return a new matrix rather than modifying in place unless explicitly allowed.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

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

Explanation

Rows become columns: the first column of the input becomes the first row of the output.

Example 2

Input

matrix = [[1,2,3],[4,5,6]]

Output

[[1,4],[2,5],[3,6]]

Explanation

For a non-square matrix, the output dimensions are swapped from 2x3 to 3x2.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.