Image Rotation LeetCode Interview Question

Please follow & like us :)

Image rotation

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?

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.

Read More About Software Engineer Preparation Guide.

Example 1:

Image Rotation
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

image rotation
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3:

Input: matrix = [[1]]
Output: [[1]]

Example 4:

Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

So, First we will process 1st row and copy elements from [0,0], [0,1], [0,2] and add them into [0,2], [1,2], [2,2] Respectively. 
123
Now, we will process 2nd row and copy elements from [1,0], [1,1], [1,2] and add them into [0,1], [1,1], [2,1] Respectively. 
456
Lastly, we will process 3rd row and copy elements from [2,0], [2,1], [2,2] and add them into [0,0], [1,0], [2,0] Respectively.

Now as we know how to solve this question we can start writing actual code.

We are solving this question using Javascript but you can use this logic using any programming language.

const imageRotation = (arr) => {
  
  for (let i = 0; i < arr.length/2; i++) {
    
    let firstRow = i;
    let lastRow = arr.length - 1 - i;
    
    for (let k = firstRow; k < lastRow; k++) {
      let temp = arr[firstRow][k];
      let offSet = k - firstRow;
      arr[firstRow][k] = arr[lastRow-offSet][firstRow];
      arr[lastRow-offSet][firstRow] = arr[lastRow][lastRow-offSet];
      arr[lastRow][lastRow-offSet] = arr[k][lastRow];
      arr[k][lastRow] = temp;
      
    }
  }

  return arr;

}

const arr = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
imageRotation(arr);