# Transpose Table

> Rows become columns. Columns become rows.

Canonical URL: <https://datadriven.io/problems/transpose_table>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a 2D matrix (list of rows, each row a list), return its transpose where element [i][j] becomes [j][i]. Assume all rows have the same length.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **matrix transposition**, converting rows to columns. It probes index manipulation and the ability to construct a new matrix with swapped dimensions.

---

### Break down the requirements

#### Step 1: Determine the output dimensions

If the input is m x n, the output is n x m.

#### Step 2: Map each element to its transposed position

Element at `[i][j]` moves to `[j][i]` in the output.

---

### The solution

**Nested loop with swapped indices**

```python
def transpose(matrix: list) -> list:
    if not matrix or not matrix[0]:
        return []
    rows = len(matrix)
    cols = len(matrix[0])
    result = []
    for c in range(cols):
        new_row = []
        for r in range(rows):
            new_row.append(matrix[r][c])
        result.append(new_row)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(m * n) to visit every element.
> 
> **Space:** O(m * n) for the transposed matrix.

> **Interviewers Watch For**
>
> The outer loop iterates over columns (not rows) of the input. This is the key mental shift: each column of the input becomes a row of the output.

> **Common Pitfall**
>
> Using `zip(*matrix)` produces tuples, not lists. If the output must be lists of lists, you need to convert each tuple. The explicit loop approach avoids this ambiguity.

---

## Common follow-up questions

- How would you transpose in place for a square matrix? _(Tests swapping `matrix[i][j]` with `matrix[j][i]` for `j > i`.)_
- What if rows had different lengths (ragged matrix)? _(Tests padding shorter rows with None or raising an error.)_
- How does numpy handle transposition? _(Tests knowledge of `array.T` and the zero-copy view semantics.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/transpose_table)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.