533. Transpose Matrix
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.
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]]