const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Rotate Image LeetCode Solution: The Transpose + Reverse Trick

LeetCode 48 — Rotate Image — is the classic matrix manipulation problem that teaches the transpose and reverse trick for rotating any square matrix 90 degrees clockwise in place.

8 min read|

Rotate Image (#48): transpose + reverse = 90-degree rotation

The elegant in-place matrix manipulation trick every interviewer knows

Rotate Image: The Classic Matrix Manipulation Problem

Rotate Image (#48) is one of those LeetCode problems that looks intimidating at first but has a beautifully elegant solution hiding behind the complexity. This medium-difficulty problem is a staple at Amazon, Microsoft, Google, and Meta — interviewers love it because it tests whether you can think about in-place transformations without reaching for extra memory.

The rotate image LeetCode problem asks you to rotate an n x n 2D matrix by 90 degrees clockwise, and you must do it in place. No allocating a new matrix. No extra space beyond a few variables. Just rearrange the elements where they sit. That constraint is what makes the problem interesting and what separates a good solution from a great one.

In this walkthrough, you will learn the brute force idea, then the elegant transpose + reverse trick that solves the problem in O(n^2) time and O(1) space. Once you see how it works, you will never forget it — and you will start recognizing the same pattern in related matrix problems like Spiral Matrix (#54) and Set Matrix Zeroes (#73).

Understanding the Rotate Image Problem

You are given an n x n matrix representing an image, where each cell contains a pixel value. Your task is to rotate the entire image by 90 degrees clockwise. The key constraint is that you must modify the matrix in place — you cannot allocate another 2D array and copy values into it.

To understand what a 90-degree clockwise rotation looks like, think about what happens to each element. The top row becomes the right column. The left column becomes the top row. The bottom row becomes the left column. For a specific element at position [i][j], after rotation it ends up at position [j][n-1-i] in the new arrangement.

Consider a simple 3x3 matrix: [[1,2,3],[4,5,6],[7,8,9]]. After rotating 90 degrees clockwise, it becomes [[7,4,1],[8,5,2],[9,6,3]]. Notice how the first column (1,4,7) read from bottom to top becomes the first row (7,4,1). This observation is the foundation for both the brute force and optimal approaches.

ℹ️

Interview Favorite

Rotate Image (#48) is one of the most-asked matrix problems — it appears at Amazon, Microsoft, and Google as a test of in-place manipulation skills.

The Brute Force Idea for Matrix Rotation

The most straightforward approach to rotate image is to create a new matrix and copy elements into their rotated positions. For each element at position [i][j] in the original matrix, you place it at position [j][n-1-i] in the new matrix. This mapping directly follows from the definition of a 90-degree clockwise rotation.

The brute force runs in O(n^2) time since you visit every element once, but it uses O(n^2) extra space for the new matrix. After filling the new matrix, you copy everything back into the original. This approach works and is easy to implement, but it violates the in-place constraint that the problem explicitly requires.

Some candidates try to be clever by rotating elements one at a time in a cycle — moving element A to where B should go, B to where C should go, and so on around a cycle of four positions. This approach works and uses O(1) space, but the indexing is tricky and error-prone during an interview. There is a much cleaner way.

  • Create new n x n matrix, map new[j][n-1-i] = old[i][j]
  • O(n^2) time, O(n^2) space — works but violates the in-place constraint
  • Cycle rotation is O(1) space but the index math is complex and error-prone

The Elegant Solution: Transpose + Reverse

Here is the trick that makes rotate image LeetCode one of the most satisfying problems to solve. Instead of trying to figure out complex rotation indices, you break the rotation into two simple, well-known operations: first transpose the matrix, then reverse each row. Two operations, each trivially simple, that together produce a perfect 90-degree clockwise rotation.

Step 1 is to transpose the matrix. Transposing means swapping matrix[i][j] with matrix[j][i] for all pairs where j > i (you only swap above the diagonal to avoid swapping twice). After transposing, rows become columns and columns become rows. For the 3x3 example, [[1,2,3],[4,5,6],[7,8,9]] becomes [[1,4,7],[2,5,8],[3,6,9]].

Step 2 is to reverse each row. After the transpose, simply reverse the elements in every row. The transposed matrix [[1,4,7],[2,5,8],[3,6,9]] becomes [[7,4,1],[8,5,2],[9,6,3]]. That is exactly the 90-degree clockwise rotation. The entire solution is two nested loops — one for the transpose, one for the row reversals.

The time complexity is O(n^2) because you touch each element a constant number of times. The space complexity is O(1) because you only use a single temporary variable for swapping. This is optimal — you cannot do better than O(n^2) time since you must move every element, and O(1) space is the minimum possible.

  1. 1Transpose the matrix: swap matrix[i][j] with matrix[j][i] for all j > i
  2. 2Reverse each row: for each row, swap elements from both ends moving inward
  3. 3Done — the matrix is now rotated 90 degrees clockwise
💡

Pro Tip

The entire solution is two nested loops: first transpose (swap [i][j] with [j][i] for j > i), then reverse each row. Two simple operations that together produce a 90-degree clockwise rotation.

Why Transpose + Reverse Works for Rotate Image

Understanding why this trick works is just as important as knowing it. A transpose flips the matrix across its main diagonal — the line from top-left to bottom-right. Mathematically, transposing maps each element from position [i][j] to position [j][i]. Reversing each row then maps position [j][i] to position [j][n-1-i]. Combining both: an element at [i][j] ends up at [j][n-1-i], which is exactly the formula for a 90-degree clockwise rotation.

Visualize it with the 3x3 matrix. The element 3 starts at position [0][2]. After transpose, it moves to [2][0]. After reversing row 2, it moves to [2][2]. Check: for a 90-degree clockwise rotation of [0][2] in a 3x3 matrix, the destination should be [2][3-1-0] = [2][2]. It matches perfectly.

This decomposition is not just a clever trick — it reflects a fundamental property of rotation matrices in linear algebra. A 90-degree clockwise rotation matrix can be decomposed into a transpose (reflection across the diagonal) followed by a horizontal reflection (reversing rows). Once you internalize this, you can derive rotations in any direction without memorizing formulas.

Edge Cases and Rotation Variants

The transpose + reverse approach handles edge cases gracefully. A 1x1 matrix has nothing to rotate — the transpose does nothing, the reversal does nothing, and you return immediately. A 2x2 matrix works with just one swap in the transpose step and one swap per row in the reversal step. No special cases needed.

What about rotating 180 degrees? You can apply the transpose + reverse trick twice. Alternatively, there is a simpler observation: rotating 180 degrees is the same as reversing all rows and then reversing all columns (or equivalently, reversing each row and then reversing the order of rows). Both approaches run in O(n^2) time.

For counter-clockwise (anti-clockwise) 90-degree rotation, reverse the order of operations: reverse each row first, then transpose. Alternatively, you can transpose first and then reverse each column instead of each row. Getting the order wrong is a common mistake that produces a mirror image instead of the intended rotation.

  • 1x1 matrix: no-op, return immediately
  • 2x2 matrix: works with standard algorithm, no special case
  • 180-degree rotation: apply transpose + reverse twice, or reverse rows then reverse columns
  • Counter-clockwise 90: reverse each row first, then transpose (reversed order)
  • Odd-sized matrices: center element stays in place naturally
⚠️

Watch Out

For counter-clockwise rotation, reverse the order: reverse each row FIRST, then transpose. Getting the order wrong gives you the mirror image instead of the rotation.

What Rotate Image Teaches You

Rotate image is more than a single interview question — it teaches a general problem-solving strategy. When a complex transformation seems hard to do directly, try decomposing it into simpler operations. The transpose + reverse decomposition is a perfect example: each step is trivial on its own, but together they achieve something that seems complicated.

This same pattern of decomposing matrix operations appears in Spiral Matrix (#54), where you peel layers instead of rotating, and in Set Matrix Zeroes (#73), where you use the first row and column as markers. Mastering in-place matrix manipulation gives you confidence with an entire category of problems.

The rotate matrix 90 degrees problem also reinforces the value of understanding the math behind transformations. If you know that rotation equals transpose plus reflection, you can handle any rotation direction or angle multiple without memorizing separate algorithms. Practice this pattern with YeetCode flashcards to build recall so the transpose + reverse trick is automatic when you see it in an interview.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now