Skip to content
Problem 867 · LeetCode 867(opens in a new tab)

Transpose Matrix

EasyArrays

You get a grid of numbers, matrix, with m rows and n columns. Return its transpose: the grid you get by turning every row into a column.

In the transpose, the number at row i, column j of the input sits at row j, column i. So the answer has n rows and m columns, and the top-left to bottom-right diagonal stays where it is.

Example 1

Input:  matrix = [[2, 7, 1], [8, 3, 6]]
Output: [[2, 8], [7, 3], [1, 6]]
Why:    the first column, 2 and 8, is now the first row
2 more examples and the constraints

Example 2

Input:  matrix = [[5, -1], [0, 9]]
Output: [[5, 0], [-1, 9]]
Why:    -1 and 0 swap across the diagonal; 5 and 9 stay

Example 3

Input:  matrix = [[4, 0, -3]]
Output: [[4], [0], [-3]]
Why:    one row turns into one column

Constraints

  • 1 ≤ m, n ≤ 1,000
  • 1 ≤ m × n ≤ 100,000
  • −1,000,000,000 ≤ matrix[i][j] ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Read each column as a rowO(m·n)
  2. Copy each cell to its mirrorO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 cellsVerdict
Read each column as a rowO(m·n)
Correct; reads out of order
Copy each cell to its mirrorO(m·n)
Best; reads in row order

m = rows, n = columns. Both touch every cell once; the second reads memory in order.

Edge cases to test

  • One cell. [[−6]] is its own transpose.
  • One row. [[4, 0, −3]] becomes three rows of one value each.
  • One column. [[3], [1], [2]] becomes the single row [[3, 1, 2]].
  • Square grid. The shape stays the same; only values off the diagonal move.

Common mistakes

  • Making res with m rows of n instead of n rows of m, which breaks every non-square grid.
  • Swapping in place, which only works when m equals n.
  • Swapping every pair twice in a square grid (both [i][j] and [j][i]), which undoes the work.

How to talk through it

  1. 1Clarify. Can the grid be rectangular? May I return a new grid rather than changing the input?
  2. 2State the rule. The value at row i, column j moves to row j, column i, so the shape flips from m × n to n × m.
  3. 3Size the answer. Allocate n rows of m before the loop, so every write has a place.
  4. 4Code the double loop. Read row by row and write res[j][i] = matrix[i][j].
  5. 5Test out loud. Run a single row, a single column and a square grid.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?