↓Skip to main content
  1. LeetCode/

LeetCode 48: Rotate Image

·2 mins· ·
LeetCode Medium Array Math Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-31

  • Submissions: Runtime Error ×2 → Accepted ×3

Approach
#

A 90-degree clockwise rotation moves (i, j) to (j, n - 1 - i). Split it into two steps (Matrix Template 1):

  1. Transpose: swap matrix[i][j] with matrix[j][i] (only for j > i).
  2. Reverse every row.

Both use swaps only, so extra space is O(1). Counterclockwise is a transpose followed by flipping top to bottom.

My Attempts
#

The first two used the wrong parameter name (A, NameError); every accepted version was matrix[:] = zip(*matrix[::-1]), flipping then transposing in one line, which actually builds a new matrix rather than rotating in place. The version above is truly O(1) space.

Solution
#

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 row in matrix:
            row.reverse()

Complexity
#

Time O(n²), space O(1).

Mistakes to Avoid
#

  • Transpose only half (j > i); swapping everything undoes itself.
  • matrix[:] = zip(*matrix[::-1]) passes but builds new rows (tuples, too), so it is not truly in place.

Interview Explanation
#

A clockwise quarter turn equals transposing and then reversing each row; I swap only one side of the diagonal and reverse rows in place, using O(1) extra space.

Related

LeetCode 417: Pacific Atlantic Water Flow
·3 mins
LeetCode Medium Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 417 note: walk inward from each ocean’s shore to cells no lower than the current one; cells reached from both oceans are the answer
LeetCode 973: K Closest Points to Origin
·1 min
LeetCode Medium Array Math Divide-and-Conquer Geometry
LeetCode 973 note: as in Top-K, keep a size-k max-heap (negated distances) holding the k closest points
LeetCode 73: Set Matrix Zeroes
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 note: record which rows and columns contain a 0 first, then update afterward; the follow-up uses the first row and column as markers
LeetCode 74: Search a 2D Matrix
·2 mins
LeetCode Medium Array Binary-Search Matrix
LeetCode 74 note: each row continues the previous one in sorted order, so binary search it as a 1-D array of length m × n, mapping mid to (mid // n, mid % n)
LeetCode 54: Spiral Matrix
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 54 note: keep four boundaries and walk right, down, left and up, shrinking a boundary after each side
LeetCode 59: Spiral Matrix II
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 59 note: keep four boundaries as in LC 54, but fill in 1 to n² instead of reading