# The Grid Pivot

> A different angle reveals a completely different picture.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a 2D matrix, return its transpose. Empty input returns an empty list.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **matrix transposition**, a fundamental operation in data processing and linear algebra. It probes index manipulation and the ability to construct a new matrix with swapped dimensions.

---

### Break down the requirements

#### Step 1: Determine the dimensions

The original matrix is m rows by n columns. The transpose is n rows by m columns.

#### Step 2: Build the transposed matrix

Element at `(i, j)` in the original goes to `(j, i)` in the transpose.

---

### The solution

**Index-swap transposition**

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

> **Time and Space Complexity**
>
> **Time:** O(m * n) where m and n are the matrix dimensions.
> 
> **Space:** O(m * n) for the transposed matrix.

> **Interviewers Watch For**
>
> Whether you handle non-square matrices. Many candidates assume the matrix is square and swap in place, which fails for rectangular matrices.

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

---

## Common follow-up questions

- Can you transpose in place for a square matrix? _(Tests swapping `matrix[i][j]` with `matrix[j][i]` for `i < j`.)_
- What does `zip(*matrix)` do and why does it work? _(Tests understanding of argument unpacking and zip's column-wise pairing.)_
- How would you rotate the matrix 90 degrees? _(Tests transpose + reverse rows (or reverse columns + transpose).)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_grid_pivot)
- [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.