0:00 / 0:00

Spin a square grid a quarter turn without a second grid: flip it across the diagonal, then mirror each row.

▼

The problem

LeetCode 48 (Medium). Given an n × n matrix, rotate it 90 degrees clockwise in place (no second matrix).

Example: [[1,2,3],[4,5,6],[7,8,9]] → [[7,4,1],[8,5,2],[9,6,3]].

def rotate(matrix):
    n = len(matrix)
    for i in range(n):            # transpose
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:            # reverse each row
        row.reverse()
TRY IT ON LEETCODE ▶

The solution

def rotate(matrix):
    n = len(matrix)
    for i in range(n):            # transpose
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:            # reverse each row
        row.reverse()

Transcript

Rotate Image. You're given a square grid of numbers, n by n, like the pixels of a picture. Turn the picture ninety degrees clockwise. The catch: do it in place, without building a second grid.

Take one through nine. After the turn, the rows read seven four one, eight five two, nine six three. The left column, read from the bottom up, became the top row.

The easy way copies every cell into a fresh grid, but that costs n squared extra space. Inside one grid, it's tricky. Move one to its new spot, and it lands on three, which hasn't moved yet. Every move overwrites a value you still need.

The trick is two flips. First, transpose: mirror the grid across its diagonal, so rows become columns. Then reverse each row, left to right. Two mirror images make one quarter turn.

Follow one cell. Row r, column c moves to row c, column r, then to row c, column n minus one minus r. That's exactly where a clockwise turn sends it. And each flip is just swaps between pairs, so nothing is ever overwritten.

In code, the first loop visits each cell above the diagonal and swaps it with its mirror below. The second loop reverses every row. No second grid is ever built.

Let's run it. Swap two and four, three and seven, six and eight. The diagonal stays put. Now the rows read one four seven, two five eight, three six nine. Reverse each row: seven four one, eight five two, nine six three. The picture has turned.

Each flip moves a cell at most once, so every cell moves at most twice. That's order n squared time, and you can't do better, since nearly every cell must move. Extra space is constant. Another way turns four cells at a time, ring by ring, at the same cost.

Flip across, flip each row, and the picture turns. That's Rotate Image.