~/coding-interview/leetcode-solution-rotate-image.md

Rotate Image - Leet Code Solution

// TL;DR

Transpose the matrix (swap rows and columns), then reverse each row. Two simple operations give you a 90-degree clockwise rotation in-place.

Rotate Image - Leet Code Solution

Problem Statement

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example

#Input
1 2 3
4 5 6
7 8 9

#Output
7 4 1
8 5 2
9 6 3

Matrix Rotate

Solution

Lets visualize a 2x2 matrix above. And, look at the indexes from original position to the target position.

We can easily traverse over the 2D matrix or the image layer by layer. See image below:

Image Rotate Layer

If you see the highlighted non-yellow color part. Its the outer layer which we will target in first iteration. And, Similarly the next inner layer. So, if we go layer by layer and swapping required indexes. We will get our desired rotated matrix.

Lets look at the index numbers we need to rotate. Since 2D matrix has 4 different sides. Lets look at the indexes we need to swap.

Image Rotate

# First iteration moves
(0,0) to (0,2)
(0,1) to (1,2)
(0,2) to (2,2)
(1,2) to (2,1)
(2,2) to (2,0)
(2,1) to (1,0)
(2,0) to (0,0)
(1,0) to (0,1)

Lets look at the code now.

Code

public void rotate(int[][] matrix) {
   int n = matrix[0].length;
   
   for (int layer = 0; layer < n/2; layer ++) {
      for (int i=layer; i<n-layer-1; i++) {
         //take back before swap
         int temp = matrix[layer][i];

         matrix[layer][i] = matrix[n-i-1][layer];
         matrix[n-i-1][layer] = matrix[n-1-layer][n-i-1];
         matrix[n-1-layer][n-i-1] = matrix[i][n-1-layer];
         matrix[i][n-1-layer] = temp;
      }
   }
}

Code is pretty small. Its just about playing with indexes.
Notice the first loop. If your 2D matrix is 5x5, you just need to go for layers 5/2 = 2 layers.

Go through the code, debug the code and put some print statements for indexes. You will understand it better.

Complexity

Its simply O(mxm)

Leetcode Submission Result

Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Image. Memory Usage: 39.7 MB, less than 46.89% of Java online submissions for Rotate Image.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Valid Palindrome - Leet Code Solution

Valid Palindrome - Leet Code Solution

Problem Statement Given a string, determine if it is a palindrome, considering…

Valid Anagrams - Leet Code Solution

Valid Anagrams - Leet Code Solution

Problem Statement Given two strings s and t , write a function to determine if t…

Validate Sudoku - Leet Code Solution

Validate Sudoku - Leet Code Solution

Problem Statement Determine if a 9x9 Sudoku board is valid. Only the filled…

Plus One - Leet Code Solution

Plus One - Leet Code Solution

Problem Statement Given a non-empty array of digits representing a non-negative…

Move Zeroes - Leet Code Solution

Move Zeroes - Leet Code Solution

Problem Statement Given an array nums, write a function to move all 0’s to the…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…