Ctrl K

Swap Rows and Columns

Easy
You are given a rectangular table of integers grid with m rows and n columns. Build a new table with n rows and m columns where row i is column i of the original, read from top to bottom. Put differently, the value grid[r][c] must end up at position [c][r] of the answer. Return the new table as a list of rows.
Example 1
grid=[[4, 0, -2], [7, 1, 9]] → [[4, 7], [0, 1], [-2, 9]]

The first column [4, 7] becomes the first row, the second [0, 1] the second, and the third [-2, 9] the third. A 2×3 table turns into a 3×2 one.

Example 2
grid=[[5], [6], [8]] → [[5, 6, 8]]

A single column turns into a single row.

Constraints
  • 1 ≤ m, n ≤ 1000
  • 1 ≤ m · n ≤ 10⁵
  • All rows have the same length
  • -10⁹ ≤ grid[r][c] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRepack the Tray EasyMirror and Negate a Bitmap EasyPawns the Rook Can Take EasyRolling Grid EasyNoughts and Crosses Verdict Easy
loading Python…
Input
grid=[[4, 0, -2], [7, 1, 9]]
Expected
[[4, 7], [0, 1], [-2, 9]]

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.