Swap Rows for Columns

EasyMatrixFree

Problem

A spreadsheet export stores one record per row, but the reporting tool expects one record per column. Given an m × n grid of integers, return its transpose: an n × m grid where the value at row i, column j is the original value at row j, column i.

The grid is not necessarily square.

Example 1

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

The first row 1, 2, 3 becomes the first column; the second row becomes the second column.

Example 2

Input:
grid = [[7]]
Output:
[[7]]

Constraints

  • 1 ≤ m, n ≤ 1000
  • 1 ≤ m · n ≤ 10^5
  • -10^9 ≤ grid[i][j] ≤ 10^9

Hint

Show the first hint

Start by working out the shape of the answer: how many rows and columns does it have?

Walkthrough

How to approach it

01Clarify before coding

  • Can the grid be rectangular? Yes, so an in-place swap across the diagonal is impossible in general: the shape changes.
  • May I return a new grid? Yes, the result is returned, not written into the input.
  • Can rows be empty? No, m and n are both at least 1.

02Brute force

There is no meaningfully slower approach: every value must be written once. A common clumsy version appends to lists while searching for the right column, but it still touches each cell.

Cost: O(m · n) time and O(m · n) space for the output, which is optimal because the output itself has m · n cells.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.