The Grid Pivot

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Citadel

Problem

A metrics export arrives as matrix, a list of equal-length rows of readings. Return that grid turned on its side, so each original column becomes a row, and return an empty list when matrix is empty.

A different angle reveals a completely different picture.

Example 1

Input:

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

Output:

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

Example 2

Input:

matrix = [[1,2],[3,4]]

Output:

[[1,3],[2,4]]

Worked solution and explanation

The trap hiding in a rectangle

Strip the costume off and this is a coordinate swap: the value at position (i, j) in the input has to land at (j, i) in the result. Anyone can recite that. What actually separates candidates is noticing the shape CHANGES: an m-by-n grid comes back n-by-m. The people who stumble reach for the textbook square-matrix trick of swapping matrix[i][j] with matrix[j][i] in place, and that only works when rows equal columns. Hand it the 2-by-3 example and an in-place swap walks straight off the end of a row.

The solution

Pivot with zip
def transpose_matrix(matrix: list) -> list:
    return [list(column) for column in zip(*matrix)]

Unpacking the rows into zip pairs them column-wise; an empty matrix unpacks to nothing, so this returns [] for free.

zip(*matrix) spreads the rows out as separate arguments, then zip stitches the first element of each into one tuple, the second into the next, and so on. That IS the column-wise read you want, with no manual index bookkeeping. The one catch is the output type.

In-place square swap
Swapping matrix[i][j] with matrix[j][i] for i < j mutates the input and only works when rows == columns. Feed it a rectangle and it indexes out of bounds.
Build a fresh grid
Reading columns into new rows handles any m-by-n shape, never touches the input, and is the same O(m*n) work. This is the answer to ship.

Common follow-up questions