CodeArchon

mediumMath & GeometryAmazonMicrosoft

Portrait Rotator

A photo-viewer rotates an n×n image 90° clockwise in place without extra buffers.

Given an n×n 2D matrix representing an image, rotate it 90 degrees (clockwise) in place.

Choose approach

1
2
3
4
5
6
7
8
9
1/3
Narrationstep 1 of 3

Start — transpose (swap over main diagonal).

1def rotate(matrix):
2 n = len(matrix)
3 for i in range(n):
4 for j in range(i + 1, n):
5 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
6 for row in matrix: row.reverse()
Variables
n=3

How to think about it

  1. Linear-algebra identity: Rot90 = Transpose · ReverseRows.
  2. In-place swaps avoid extra memory.

Edge cases to catch in interview

  • 1×1 -> unchanged.
  • Even and odd n handled identically.

Examples

Example 1[[3,1],[4,2]]
{"grid":[[1,2],[3,4]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed