PPractick

DSA interview question

Rotate a Matrix by 90 Degrees

Medium · Algorithms · Topics: array, matrix, transpose

The problem

A photo editor stores images as n × n grids of pixel values, and the "rotate right" button must turn the image 90 degrees clockwise in place, since phones don't have memory to spare for a second copy of a large image. Mapping each pixel directly to its new position and writing it in place would overwrite pixels you still need. The elegant solution is two simple in-place steps: transpose the matrix (swap across the main diagonal), then reverse each row.

Example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] → [[7, 4, 1], [8, 5, 2], [9, 6, 3]].

Function signature

void rotate(vector<vector<int>>& m);  // n x n matrix, rotated 90 degrees clockwise in place

Test cases

Input mOutputExplanation
[[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]The first row becomes the last column
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]][[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]4 × 4
[[1,2],[3,4]][[3,1],[4,2]]
[[1]][[1]]

(Confirm: the matrix is square; the rotation is clockwise and done in place.)

How interviewers phrase it

Clarifying questions to ask

  1. Clockwise or counter-clockwise?
  2. Is the matrix square?
  3. Must it be in place?

Follow-ups to expect

  1. "Where does element (i, j) go?"
  2. "Why does transpose-then-reverse work?"
  3. "How do you rotate counter-clockwise?"
  4. "Is there a one-pass alternative?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in