#867

Transpose Matrix

Easy Index swap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the transpose of a matrix (rows become columns). The matrix may not be square.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: rows become columns.

Why this works: the cell at (r, c) moves to (c, r), so the result is n × m.

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

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

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Swapping in place — impossible for non-square matrices.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n).
  • Space: O(m·n) for the output.
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon