DSA interview question
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]].
void rotate(vector<vector<int>>& m); // n x n matrix, rotated 90 degrees clockwise in place
Input m | Output | Explanation |
|---|---|---|
[[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in