Transpose Matrix (LeetCode 867): Solution and Explanation

Easy
Array
Matrix
Simulation

Given an m x n integer matrix, return its transpose: the matrix flipped over its main diagonal. Every value at matrix[r][c] moves to result[c][r], so the answer has n rows and m columns.

Intuition

Picture the main diagonal running from the top-left corner down and to the right. Transposing reflects every cell across that line, so a cell at row r, column c lands at row c, column r. Cells on the diagonal, where r equals c, do not move.

Another way to see it: row r of the input becomes column r of the output. Reading the first row left to right is the same as reading the first column of the answer top to bottom.

For a square matrix you could swap matrix[r][c] with matrix[c][r] in place for every c > r. But when m != n the shape itself changes, a 2 x 3 matrix becomes 3 x 2, so the answer must live in a freshly allocated n x m matrix.

Approach: Copy into a new n x m matrix

  1. Read m = len(matrix) and n = len(matrix[0]).
  2. Allocate result with n rows and m columns.
  3. For each r in 0..m-1 and each c in 0..n-1, set result[c][r] = matrix[r][c].
  4. Return result.

Step-by-step example

matrix = [[1,2,3],[4,5,6]]
  1. m = 2 and n = 3, so allocate a 3 x 2 result filled with zeros.
  2. Row 0 = [1,2,3]: result[0][0] = 1, result[1][0] = 2, result[2][0] = 3. Column 0 of the result is now 1, 2, 3.
  3. Row 1 = [4,5,6]: result[0][1] = 4, result[1][1] = 5, result[2][1] = 6. Column 1 is now 4, 5, 6.
  4. The result is [[1,4],[2,5],[3,6]].

Code: Python, Java, C++

1class Solution:
2    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
3        m, n = len(matrix), len(matrix[0])
4        result = [[0] * m for _ in range(n)]
5        for r in range(m):
6            for c in range(n):
7                result[c][r] = matrix[r][c]
8        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each of the m * n values is read once and written once.

Space

O(m * n)

The output matrix holds m * n values. Apart from the output, only the loop indices are used.

Other approaches

In-place swap (square only) (time O(n^2), space O(1))

When m == n, swap matrix[r][c] with matrix[c][r] for every c > r. This avoids the extra matrix, but it cannot handle rectangular input, which the problem allows.

Built-in zip (time O(m * n), space O(m * n))

In Python, [list(col) for col in zip(*matrix)] produces the transpose in one line. It does the same work under the hood.

Common mistakes

  • Allocating the result as m x n instead of n x m. It only works by accident when the matrix is square.
  • Trying to transpose in place on a rectangular matrix. The shape changes, so values have nowhere to go.
  • Swapping in place over every (r, c) pair on a square matrix. Each pair is swapped twice and the matrix ends up unchanged; only swap when c > r.
  • Building the rows with [[0] * m] * n in Python, which makes every row the same list object.

Frequently asked questions

What does the transpose of a matrix mean?

It is the matrix reflected over its main diagonal. The element at row r, column c moves to row c, column r, so rows become columns and an m x n matrix becomes n x m.

Can the transpose be done in place?

Only when the matrix is square. Then you swap each pair above the diagonal with its mirror below it. For rectangular input the dimensions change, so you need a new matrix.

How is Transpose Matrix related to Rotate Image?

Rotating a square matrix 90 degrees clockwise is a transpose followed by reversing each row. Transpose Matrix is the first half of that trick.

What is the time and space complexity of Transpose Matrix?

O(m * n) time to copy every value, and O(m * n) space for the returned matrix, with O(1) extra space besides it.