The Spin Doctor

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

Domain
Python
Difficulty
medium
Seniority
L4
Asked in
Sigmoid

Problem

Given an n x n matrix, return a new matrix rotated 90 degrees counter-clockwise. Do not mutate the input.

Ninety degrees, but which way?

Example

Input:

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

Output:

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

Worked solution and explanation

Why this problem exists in real interviews

This tests matrix transformation and index manipulation. 90-degree counter-clockwise rotation requires understanding the coordinate mapping between source and destination positions, which probes spatial reasoning.


Break down the requirements

Step 1: Determine the dimension n

The matrix is n x n. The output has the same dimensions.

Step 2: Map each element to its rotated position

For counter-clockwise 90 degrees: the first row becomes the last column, the last row becomes the first column.

Step 3: Build a new matrix without modifying the input

Allocate a fresh n x n matrix and populate it using the coordinate mapping.


The solution

Direct index mapping for counter-clockwise rotation
def rotate_ccw(matrix: list) -> list:
    n = len(matrix)
    rotated = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(matrix[j][n - 1 - i])
        rotated.append(row)
    return rotated

Common follow-up questions