Skip to content
mlmentorship

Rotate Image

Rotate a square matrix 90 degrees clockwise in place.

Published · 12 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Rotate Image

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. An n-by-n integer matrix whose rows are distinct mutable lists; [] is allowed. Output. Change the supplied matrix into its ninety-degree clockwise rotation and return None. Rules. Do not return a separate rotated matrix. Values may repeat or be negative. The input must be square, not ragged or rectangular with unequal dimensions. External references observe changed cells and possibly reordered row objects. Empty input remains empty. Example. [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]]. The original bottom-left value 3 becomes the new top-left value.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Reverse row order, then swap every above-diagonal cell with its reflected below-diagonal partner.

Problem trace

Equivalent two-by-two recipe: transpose, then reverse each row

Worked example: transpose then reverse each row rotates coordinates clockwiseInput rows (1,2) and (3,4) rotate to (3,1) and (4,2). Reversing columns after transposing would rotate the other direction.Two coordinate changes form theclockwise quarter-turnOriginal coordinates1234Transpose: exchange row and column1324Reverse each row horizontally3142Original one stays at top-left aftertranspose, then moves to top-rightafter row reversal.
Read it this way: Input rows (1,2) and (3,4) rotate to (3,1) and (4,2). Reversing columns after transposing would rotate the other direction. Where does original top-left one end after both coordinate changes?
Full interview answer 12 min read
Reading depth

Rotate a square matrix by ninety degrees clockwise while updating the supplied matrix in place.

Problem

Input. An n-by-n integer matrix whose rows are distinct mutable lists; [] is allowed.

Output. Change the supplied matrix into its ninety-degree clockwise rotation and return None.

Rules. Do not return a separate rotated matrix. Values may repeat or be negative. The input must be square, not ragged or rectangular with unequal dimensions. External references observe changed cells and possibly reordered row objects. Empty input remains empty.

Example. [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]]. The original bottom-left value 3 becomes the new top-left value.

Picture

For [[1,2], [3,4]], reversing row order produces [[3,4], [1,2]]. Swapping the off-diagonal pair produces [[3,1], [4,2]]. Reversal sends (row, col) to (n - 1 - row, col); transposition exchanges those coordinates.

Problem trace

Three-by-three code fixture: reverse row order, then transpose

Input and goalRotate a square matrix 90 degrees clockwise in place.
Start with the original coordinatesThe original square contains three rows: [1,2,3], [4,5,6], and [7,8,9].
1value 12value 23value 34value 45value 56value 67value 78value 89value 9
actioninitialize
value 1
(0, 0)
value 2
(0, 1)
value 3
(0, 2)

Recognize it
Use this transformation for a square matrix that must rotate 90 degrees clockwise without allocating a second matrix.
Keep true
After row reversal, values have moved from (r,c) to (n-1-r,c); after transposition, each reaches (c,n-1-r), exactly its clockwise coordinate.
Reuse it
Derive a target coordinate mapping, then factor it into simple reversible transforms whose in-place loops visit each swap pair exactly once.
The original square contains three rows: [1,2,3], [4,5,6], and [7,8,9]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Where does original cell (0,2) go after both operations? Why must each transpose pair be swapped only once?
Reference drawing

Problem trace

Transpose once, then reverse rows to turn the matrix clockwise

Worked example: transpose then reverse each row rotates coordinates clockwiseInput rows (1,2) and (3,4) rotate to (3,1) and (4,2). Reversing columns after transposing would rotate the other direction.Two coordinate changes form theclockwise quarter-turnOriginal coordinates1234Transpose: exchange row and column1324Reverse each row horizontally3142Original one stays at top-left aftertranspose, then moves to top-rightafter row reversal.
Execution trace
Input and goalRotate a square matrix 90 degrees clockwise in place.
Start with the original coordinatesThe original square contains three rows: [1,2,3], [4,5,6], and [7,8,9].
1value 12value 23value 34value 45value 56value 67value 78value 89value 9
actioninitialize
value 1
(0, 0)
value 2
(0, 1)
value 3
(0, 2)

Recognize it
Use this transformation for a square matrix that must rotate 90 degrees clockwise without allocating a second matrix.
Keep true
After row reversal, values have moved from (r,c) to (n-1-r,c); after transposition, each reaches (c,n-1-r), exactly its clockwise coordinate.
Reuse it
Derive a target coordinate mapping, then factor it into simple reversible transforms whose in-place loops visit each swap pair exactly once.
The original square contains three rows: [1,2,3], [4,5,6], and [7,8,9]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Where does original cell (0,2) go after both operations? Why must each transpose pair be swapped only once?
Read it this way: Input rows (1,2) and (3,4) rotate to (3,1) and (4,2). Reversing columns after transposing would rotate the other direction. Where does original top-left one end after both coordinate changes?

Only swap above the diagonal, where col > row. Visiting both sides would swap every pair twice and undo transposition.

Code

def rotate_image(matrix: list[list[int]]) -> None:
   matrix.reverse()
   for row in range(len(matrix)):
      for col in range(row + 1, len(matrix)):
         matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]

Cost: time and space.

Bounds count cell operations, not the bit lengths of stored integers.

Change the Requirement

Rotate Counterclockwise

New task: Rotate the same square matrix counterclockwise.

Picture and change: Transpose first, then reverse row order: (row, col) becomes (n - 1 - col, row).

Code: This complete alternative retains the original mutation contract.

def rotate_counterclockwise(matrix: list[list[int]]) -> None:
   for row in range(len(matrix)):
      for col in range(row + 1, len(matrix)):
         matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
   matrix.reverse()

Check: [[1,2], [3,4]] becomes [[2,4], [1,3]].

Use when: Orientation reverses; costs remain time and constant workspace.

Preserve a Rectangular Input

New task: Return a rotated copy of a rectangular matrix.

Picture and change: An rows-by-cols input becomes cols-by-rows; allocate independent output rows.

Code: The input must be rectangular; empty dimensions return [].

def rotated_copy(matrix: list[list[int]]) -> list[list[int]]:
   rows = len(matrix)
   cols = len(matrix[0]) if rows else 0
   return [
      [matrix[row][col] for row in range(rows - 1, -1, -1)]
      for col in range(cols)
   ]

Check: [[1,2,3], [4,5,6]] produces [[4,1], [5,2], [6,3]]; the input stays unchanged.

Use when: Shape or ownership prevents square in-place swaps. Time and output storage are .

Reconstruct

Why exclude aliased rows?

Reasoned answer

row = [1,2]; matrix = [row, row] has two logical rows but only one underlying row object. A cell update changes both logical rows, violating the coordinate-permutation model. Build independent rows before applying the square reference.