# Rotate Image - Leet Code Solution

September 04, 2020

## 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``````

## 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:

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.

``````# 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.

## Similar Posts

### Crawler Log Folder - minimum number of operations needed to go back to the main folder after the change folder operations.

Problem The Leetcode file system keeps a log each time some user performs a…

### Single Number - Leet Code Solution

Problem Statement Given a non-empty array of integers, every element appears…

### Calculate Max Profit - Buy and Sell Stocks Multiple Times - Leet Code Solution

Problem Statement Say you have an array prices for which the ith element is the…

### Young Tableau problem - Cormen

Young Tableau A a X b matrix is Young Tableau if all rows(from left to right…

### What is Heap Data Structure

Its a tree based data structure which is a complete binary tree(all nodes have…

### Determine if a string has all unique characters

Problem Implement an algorithm to determine if a string has all the characters…

## Latest Posts

### Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…

### How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

Introduction There are some cases, where I need another git repository while…

### How to Fetch Multiple Credentials and Expose them in Environment using Jenkinsfile pipeline

Introduction In this post, we will see how to fetch multiple credentials and…

### Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Introduction I have an automation script, that I want to run on different…

### Jenkinsfile - How to Create UI Form Text fields, Drop-down and Run for Different Conditions

Introduction I had to write a CICD system for one of our project. I had to…

### Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…