228. Swap Rows for Columns

A spreadsheet stores a table of numbers in the grid grid, with m rows and n columns. The spreadsheet has a swap rows for columns command: after it runs, what used to be the first row becomes the first column, what used to be the second row becomes the second column, and so on. In other words the cell at row i, column j moves to row j, column i.

Return the table after the command. Note that the table does not have to be square, so the answer has n rows and m columns.

Example 1

Input:
grid = [[3,8,1],[6,2,9]]
Output:
[[3,6],[8,2],[1,9]]
Explanation:

The first row 3,8,1 becomes the first column and the second row 6,2,9 becomes the second column, giving a grid with 3 rows and 2 columns.

Example 2

Input:
grid = [[4]]
Output:
[[4]]
Explanation:

A one-cell table is unchanged.

Example 3

Input:
grid = [[7,0],[5,5],[2,9],[1,4]]
Output:
[[7,5,2,1],[0,5,9,4]]
Explanation:

A tall 4x2 table turns into a wide 2x4 table: the first column 7,5,2,1 becomes the first row, and the second column 0,5,9,4 becomes the second row.

Constraints

1 ≤ grid.length, grid[0].length ≤ 100
-1000 ≤ grid[i][j] ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(m × n)
Space
O(m × n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…