The Quarter Turn

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
Citadel

Problem

We store map tiles as square grids of pixel values, and the render step turns each one a quarter-turn clockwise before drawing it. Rotate the grid clockwise in place and return the same grid.

One rotation changes everything.

Example 1

Input:

matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output:

[[7,4,1],[8,5,2],[9,6,3]]

Example 2

Input:

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

Output:

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

Worked solution and explanation

What this problem is really testing

Strip the map-tile costume and this is a coordinate remap: the value at row i, column j has to land at row j, column n-1-i. Anyone can see it's a rotation. The separator between candidates is direction and staging. A transpose alone only mirrors the grid, transpose-then-reverse-columns rotates the wrong way, and writing a cell before reading its old value corrupts the data mid-flight. The clean move is to compose two dead-simple in-place operations: transpose across the main diagonal, then reverse each row.


Break down the two moves

Step 1: Transpose the grid

Swap matrix[i][j] with matrix[j][i] for every j > i. That mirrors the grid along the main diagonal. Iterating only the upper triangle matters: touch both (i,j) and (j,i) and you swap each pair twice, undoing the transpose.

Step 2: Reverse each row

Reverse each row in place with a two-pointer swap. Transpose put the columns in the right places but top-to-bottom; reversing each row flips them left-to-right to finish the clockwise turn.


The solution

Transpose, then reverse each row
def rotate_90_clockwise(matrix: list) -> list:
    n = len(matrix)
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:
        left = 0
        right = len(row) - 1
        while left < right:
            row[left], row[right] = row[right], row[left]
            left += 1
            right -= 1
    return matrix

Common follow-up questions