Cracking The Coding Interview Together – Problem 1.7: Rotate Matrix
Hope you're having a great day and making steady progress in your interview prep. I, on the other hand, am back with another classic that looks deceptively simple—but once you start explaining it out loud to an interviewer, you quickly realize there’s more going on than just “rotate a bunch of numbers around.”
Anyway, enough of my rambling. Let’s get into today's problem!We always follow the format as follows
- Understand the problem statement together
- Ask any questions, that you would like to ask the interviewer
- I would urge you to take your time here and try to come up with your own solution before going forward
- Think how you would go about solving the problem(you would be talking out loud in front of the actual interviewer)
- Write code and understand how it works and explain it to your interviewer
Problem statement
Given an image represented by an NxN matrix, where each pixel in the image is 4
bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
Analyse the problem statement together
You’re given an image represented as an N x N matrix. Every pixel is 4 bytes - but honestly, that detail isn’t going to change how we approach the logic. The key point is: you must rotate the matrix by 90° and ideally do it in-place.
So, for example:
1 2 3
4 5 6
7 8 9Rotated 90° clockwise becomes:
7 4 1
8 5 2
9 6 3Visually this makes sense. Logically you may think, “Cool, this shouldn’t be too bad.”
And your interviewer quietly smiles because they know exactly what’s coming.
Take some time and try to dig deep to see if there is anything unclear to you.
Questions for the interviewer
Every good interview solution starts with the right questions. If I were sitting in front of an interviewer, I’d ask:
- Is the matrix guaranteed to be square (NxN)?
Most likely yes, but clarify. If the answer is no, a rotation in-place becomes much harder. - Should the rotation be clockwise or counter-clockwise?
The default expectation is clockwise. If not specified, confirm. - Do we have to rotate in place?
If they say yes (and they usually will), you know you’re being tested on matrix manipulation fundamentals. - Is the matrix mutable?
Probably yes, but if for some reason you’re given an immutable object, the strategies change.
Simple questions, but they show you’re thinking. These questions show clarity of thought and prevent misunderstandings.
Think about the Solution
Before you scroll further, pause.
Imagine you're in the interview. You have a pen. A whiteboard. A 3x3 or 4x4 matrix.
Try rotating it manually and observe the pattern.
Think about:
- What happens to the top row?
- Where does the left column go?
- What happens if you rotate the matrix layer by layer?
Give yourself that minute.
Now let’s talk approaches.
Brute Force Idea:
The brute-force strategy is quite literally:
- Create a second
N x Nmatrix. - For every position
(i, j)in the original matrix,
place it into its rotated position in the new matrix.
Mathematically:
new[j][N-1-i] = old[i][j]This absolutely works.
Is it “acceptable”? Yes.
Is it what your interviewer wants? Probably not.
Because they explicitly asked: Can you do this in-place?
Let’s keep the brute force solution in our pocket (it’s great for initial correctness), but now we aim for the elegant version.
Optimal Approach - Rotate In-Place, Layer by Layer
This is where the light bulb moment happens.
Think of the matrix as an onion — composed of layers.
For example, in a 4x4 matrix:
Layer 0 → the outer frame
Layer 1 → the inner 2x2Each layer can be rotated independently.
In each layer:
- You take top → right
- left → top
- bottom → left
- right → bottom
But here’s the key insight:
A 90° rotation is basically a 4-way swap.
Let’s visualize for a specific cell in layer l:
temp = top[i][j]
top[i][j] = left[n-1-j][i]
left[n-1-j][i] = bottom[n-1-i][n-1-j]
bottom[n-1-i][n-1-j] = right[j][n-1-i]
right[j][n-1-i] = tempIf this looks overwhelming, don’t worry—when you write it step by step, it becomes a pattern.
Also notice:
We only iterate up to n / 2 layers because each rotation handles the outer and then inner squares.
The key insight is that rotation happens layer by layer, like peeling an onion from the outside toward the center. Each layer forms a ring of elements, and rotating the matrix simply means rotating each ring. Within a ring, every element moves into the position previously held by another element in a perfect 4-way cycle: top → right → bottom → left → top. Once this pattern clicks, the “messy index manipulation” suddenly becomes predictable and almost mechanical. You’re not memorizing formulas — you’re just shifting elements around the ring in a structured way, which gives us a clean, in-place rotation with optimal space usage.
Write code and explain
Since you have the complete understanding of the solution you explain the solution and write the code. Implementation could be as follows:
public static boolean rotateMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix.length != matrix[0].length) {
return false; // must be NxN
}
int n = matrix.length;
// We rotate layer by layer
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - 1 - layer;
for (int i = first; i < last; i++) {
int offset = i - first;
// Save top
int top = matrix[first][i];
// left → top
matrix[first][i] = matrix[last - offset][first];
// bottom → left
matrix[last - offset][first] = matrix[last][last - offset];
// right → bottom
matrix[last][last - offset] = matrix[i][last];
// top → right
matrix[i][last] = top;
}
}
return true;
}
What you should tell your interviewer while writing this:
- “We rotate the matrix in layers.”
- “For each layer, we perform a series of four swaps.”
- “We only need O(1) additional memory.”
- “Time complexity is O(N²) because we touch each element once.”
Show confidence and clarity — the code is straightforward once you break down the logic.
Time Complexity - O(N²)
We must touch each element once, which is unavoidable for a matrix rotation.
Space Complexity - O(1)
Everything is done in-place with only temporary variables.
Final Thoughts
And that, my friend, was Problem 1.7.
A problem that looks innocent, then immediately attacks you with indices, layers, and swapping logic—but once you get the hang of it, you genuinely start to enjoy matrix-manipulation problems.
If you’re following the series, you’ll know this is exactly the kind of problem interviewers love: simple to state, but tests your ability to reason, break down patterns, and write correct code under pressure.
As always, if you’re enjoying this series or want me to tackle a specific question next, drop your thoughts in the comments or email me at [email protected].
Until next time - enjoy your prep and keep pushing forward!
Happy Coding!
Member discussion