LeetCode 48: Rotate Image — Python Solution

LeetCode 48: Rotate Image is a Medium matrix problem. This Python walkthrough develops a transpose then reverse rows solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicMatrix
Reusable patterntranspose then reverse rows
ComplexityO(n^2) time and O(1) extra space

Recognizing the pattern

Matrix problems become manageable when row, column, layer, or neighbor boundaries are explicit rather than inferred inside nested loops.

For this problem specifically, transpose across the main diagonal, then reverse every row to obtain a clockwise quarter-turn in place. The invariant worth writing beside the code is: After transposition and row reversal, original cell (r,c) reaches (c,n-1-r).

Step-by-step algorithm

  1. Identify the input state consumed by rotate(matrix) and initialize the data required by the transpose then reverse rows pattern.
  2. Transpose across the main diagonal, then reverse every row to obtain a clockwise quarter-turn in place.
  3. After each update, verify the page’s central invariant: After transposition and row reversal, original cell (r,c) reaches (c,n-1-r).
  4. Finish only after the boundary behavior is covered: The operation mutates the square matrix; a 1×1 matrix remains unchanged.

Python solution

class Solution:
    def rotate(self, matrix):
        n = len(matrix)
        for r in range(n):
            for c in range(r + 1, n):
                matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
        for row in matrix: row.reverse()

Reading the implementation

The main entry point is rotate(matrix). The named working state includes n; those variables make the transpose then reverse rows state visible instead of hiding it in incidental control flow.

The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, transpose across the main diagonal, then reverse every row to obtain a clockwise quarter-turn in place.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Transpose across the main diagonal, then reverse every row to obtain a clockwise quarter-turn in place. Each update records the current item without invalidating earlier decisions; consequently, after transposition and row reversal, original cell (r,c) reaches (c,n-1-r).

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n^2) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An auxiliary matrix can make reads and writes independent, while marker or boundary techniques trade that clarity for lower space use. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

matrix=[[1,2,3],[4,5,6],[7,8,9]]; Solution().rotate(matrix); assert matrix == [[7,4,1],[8,5,2],[9,6,3]]

Common mistakes and edge cases

  • Problem-specific boundary: The operation mutates the square matrix; a 1×1 matrix remains unchanged.
  • Pattern-level pitfall: Rectangular inputs, one-row layers, and one-column layers expose off-by-one errors that square examples often hide.
  • Invariant check: after every update, confirm that after transposition and row reversal, original cell (r,c) reaches (c,n-1-r).

Interview review checklist

  • Explain why transpose then reverse rows matches the structure of this input.
  • State the invariant in one sentence before tracing code: After transposition and row reversal, original cell (r,c) reaches (c,n-1-r).
  • Derive O(n^2) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: The operation mutates the square matrix; a 1×1 matrix remains unchanged.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 54. Spiral Matrix · Next: 73. Set Matrix Zeroes