533/670

533. Transpose Matrix

Easy

You are given an m × n integer grid matrix — a list of m rows, each holding n values. Return its transpose: the n × m grid whose rows are the columns of the original. Concretely, the value sitting at row i, column j of the input must end up at row j, column i of the output.

When the grid is not square the shape flips — a wide matrix comes back tall — so the answer generally needs its own freshly allocated grid rather than an in-place shuffle.

Transposing a 2 × 3 matrixEvery value at row i, column j moves to row j, column i. The gold row [1, 2, 3] of the 2×3 input reappears as the gold first column of the 3×2 output.
matrix (2 × 3)123456row 0(i, j) → (j, i)row 0 becomes column 0transpose (3 × 2)142536

Example 1:

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

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

Explanation: The 2×3 input flips into a 3×2 output. Column 0 of the input, [1, 4], becomes row 0 of the answer; column 1 becomes [2, 5]; column 2 becomes [3, 6].

Example 2:

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

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

Explanation: A square matrix keeps its 3×3 shape; every value is mirrored across the main diagonal, and the diagonal 1, 5, 9 stays where it is.

Constraints:

  • 1 ≤ m, n ≤ 1000
  • 1 ≤ m * n ≤ 10⁵
  • -10⁹ ≤ matrix[i][j] ≤ 10⁹

Hints:

Track one value's journey: whatever lives at row i, column j of the input must land at row j, column i of the output. That single index swap is the entire problem.

Allocate a fresh n × m grid up front, then loop over every cell of the input and assign result[j][i] = matrix[i][j]. Resist swapping in place — the shape changes whenever m ≠ n.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: [[1, 4], [2, 5], [3, 6]]