Skip to the solution
MediumDSA14 min read

How do you rotate an N×N matrix by 90 degrees in place?

708 views

The problem

Question presented to candidate: "You are given an n by n matrix as a Python list of lists, for example an image. Rotate it 90 degrees clockwise, in place: modify the given lists rather than returning a new matrix."

What a strong answer should cover:

  • The mapping: cell (r, c) goes to (c, n - 1 - r); a copy-based version is easy but O(n²) extra space.
  • Transpose (swap m[i][j] with m[j][i] for j > i only), then reverse each row; O(n²) time, O(1) extra space.
  • The alternative four-way swap per layer, and the counter-clockwise variant (transpose, then reverse the row order).
  • Only square matrices can be rotated in place; R×C becomes C×R.
  • Python specifics: list(zip(*m[::-1])) is a neat one-liner but builds new tuples, row.reverse() is in place while row = row[::-1] only rebinds a name, and [[0] * n] * n creates n references to the same row.

Clarifying questions expected:

  • "Clockwise or counter-clockwise, and is it always square?"
  • "Is a new matrix acceptable, or must it be in place?"

Code / implementation expected: Yes — a Python rotate(matrix) that transposes and reverses rows in place.

  • matrix
  • in-place

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read · 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTranspose, then reverse each row (1x1 to 4x4)
PythonFour-way layer swap vs transpose + reverse vs copying, counting writes
PythonCounter-clockwise, 180 degrees, four turns, and a non-square matrix

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 72 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the kth smallest element in a BST?

Continue