Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Python: Transpose and Reverse, O(1) Space

Practice O(n^2) Read the full explanation

You get a square grid matrix of integers, with n rows and n columns.

Rotate it a quarter turn clockwise, like turning a photo onto its right side.

matrix is a list of rows. Each row is a list of integers. Row 0 is the top row. Column 0 is the leftmost column.

Work in place. Change the numbers inside matrix itself, and don't fill a new grid.

Your function returns nothing. Each example's output shows matrix after the function runs.

 

Example 1:

Input: matrix = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 6]
]
Output: [
  [8, 3, 4],
  [1, 5, 9],
  [6, 7, 2]
]
Explanation: The left column, read from the bottom up, is now the top row.
The top row is now the right column.
The 5 in the center stays where it is.

Example 2:

Input: matrix = [
  [-3, 8],
  [8, 0]
]
Output: [
  [8, -3],
  [0, 8]
]
Explanation: Each number moves to the next corner clockwise:
-3 goes to the top right,
the top-right 8 goes to the bottom right,
0 goes to the bottom left,
the bottom-left 8 goes to the top left.

Example 3:

Input: matrix = [
  [7]
]
Output: [
  [7]
]
Explanation: A single number has nowhere to move.

 

Constraints:

  • n is from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · MATRIX

    Rotate Image in Python, explained

    Problem overview

    The method rotate receives a square matrix, a list of n rows with n integers each, and turns it a quarter turn clockwise, as you would turn a picture. It must do this in place: the numbers move inside matrix itself, no second matrix is built, and the method returns nothing. The result is whatever matrix holds after the call.

    For this matrix:

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

    the rotated matrix is:

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

    The left column, read from the bottom up (7, 4, 1), becomes the top row, and the top row becomes the right column. The required time is O(n²), which is the size of the matrix, and the extra space is O(1).

    Approach: two simple flips make one rotation

    The direct way to rotate is to work out where each cell goes: the number at row i, column j lands at row j, column n - 1 - i. Doing that in place means moving four cells in a cycle and keeping track of the corners, which is easy to get wrong. Building a second matrix is easy but uses O(n²) extra space, which the lesson rules out.

    A cleaner idea splits the rotation into two flips that are each easy to do in place:

    1. Transpose the matrix: flip it over its main diagonal, the line from the top-left corner to the bottom-right one. The number at row i, column j swaps places with the one at row j, column i, so every row becomes the column with the same number.
    2. Reverse every row. After the transpose, row i holds the old column i from top to bottom, and a clockwise turn needs that column from bottom to top.

    On the example, the transpose gives:

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

    Reversing each row then gives [7, 4, 1], [8, 5, 2] and [9, 6, 3], which is the rotated matrix.

    Step by step

    1. Store the size in n. The matrix is square, so it is both the number of rows and the number of columns.
    2. Loop over the rows with i in range(n) to start the transpose.
    3. Loop over the columns to the right of the diagonal with j in range(i + 1, n). Each pair of mirrored cells is visited exactly once. If j started at 0, every pair would be swapped twice and the second swap would undo the first.
    4. Swap the two mirrored cells, matrix[i][j] and matrix[j][i], with one tuple assignment.
    5. Start a second loop over the rows to reverse them, after the transpose is complete.
    6. Reverse each row in place with its reverse() method.

    The solution in Python

    class Solution:
        def rotate(self, matrix: List[List[int]]) -> None:
            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 i in range(n):
                matrix[i].reverse()
    

    The Python details that matter here:

    • Tuple assignment swaps without a temporary. Python evaluates the whole right-hand side first, producing both old values, and only then assigns them. Neither cell is overwritten before it is read.
    • reverse() works in place and returns None. Writing matrix[i] = matrix[i].reverse() would replace the row with None. The slice matrix[i][::-1] builds a new list instead, which an in-place method has no use for.
    • Rows are shared objects. The matrix is a list of lists, so matrix[i].reverse() changes the row that the caller sees. That is why a method that returns nothing can still deliver the result.
    • The method returns None. Printing Solution().rotate(m) shows None; look at m afterwards.

    Complexity

    Time: O(n²). The transpose swaps about half of the n² cells with their mirrors, and the row reversals touch every cell once more. Both are proportional to the number of cells.

    Space: O(1) extra. The method keeps only n and the loop variables. The swaps happen inside matrix, and reverse() works within each row without making a copy.

    Edge cases and common mistakes

    • A single cell. [[7]] stays [[7]]. The inner loop has nothing to swap, and reversing a one-element row changes nothing.
    • The 2 by 2 case. [[1, 2], [3, 4]] becomes [[1, 3], [2, 4]] after the transpose and [[3, 1], [4, 2]] after the reversals.
    • Swapping every pair twice. With j over range(n), the transpose undoes itself and the matrix comes out unchanged after the first stage. Starting at i + 1 avoids it.
    • Counter-clockwise by mistake. Reversing the rows is what makes the turn clockwise. Doing the reversals first and the transpose second turns the matrix counter-clockwise instead.
    • Returning a new matrix. Building a rotated copy and returning it leaves matrix unchanged, so the caller sees no rotation.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] becomes [[7, 4, 1], [8, 5, 2], [9, 6, 3]].
    • [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
    • [[7]] stays [[7]].
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free