Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Inplace rotate matrix 90 degree

Easy
0/40
Average time to solve is 12m
profile
Contributed by
53 upvotes
Asked in companies
OLX GroupOracleSamsung

Problem statement

You are given a square matrix of non-negative integers of size 'N x N'. Your task is to rotate that array by 90 degrees in an anti-clockwise direction without using any extra space.

For example:

For given 2D array :

    [    [ 1,  2,  3 ],
         [ 4,  5,  6 ],
         [ 7,  8,  9 ]  ]

After 90 degree rotation in anti clockwise direction, it will become:

    [   [ 3,  6,  9 ],
        [ 2,  5,  8 ],
        [ 1,  4,  7 ]   ]
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.

The first line of each test case contains an integer 'N' representing the size of the square matrix ARR.

Each of the next 'N' lines contains 'N' space-separated integers representing the elements of the matrix 'ARR'.
Output Format:
For each test case, return the rotated matrix.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 ≤ T ≤ 50
1 ≤ N ≤ 100
1 ≤ ARR[i][j] ≤ 10^9

Time Limit: 1 sec 
Sample Input 1:
2
3
1  2  3
4  5  6
7  8  9
4
1  2  3  4 
5  6  7  8 
9 10 11 12 
13 14 15 16
Sample Output 1:
3  6  9 
2  5  8 
1  4  7
4  8 12 16 
3  7 11 15 
2  6 10 14 
1  5  9 13
Explanation of Input 1:
(i) The array has been rotated by 90 degrees in an anticlockwise direction as the first row is now the first column inverted and so on for second and third rows.

(ii) The array has been rotated by 90 degrees in an anticlockwise direction as the first row is now first column inverted and so on for second, third and fourth rows.
Sample Input 2:
2
3
7  4  1 
8  5  2 
9  6  3
4
13  9  5  1 
14  10  6  2 
15 11 7 3 
16 12 8 4
Sample Output 2:
1  2  3
4  5  6
7  8  9
1  2  3  4 
5  6  7  8 
9 10 11 12 
13 14 15 16
Hint

Try to think of how you can rotate elements of 2D matrix one by one.

Approaches (2)
Cycle rotation
  1. There are N/2  cycles in a matrix of size ‘N’.
  2. We traverse in the matrix from the outermost cycle, i.e. (0,0) to innermost cycle i.e. ((N/2)-1, (N/2)-1).
  3. For each cycle, we’ll swap the elements of the matrix in a group of four elements i.e. for each ‘i’ <= ‘j’ < ‘N-i-1’ for each 0 <= ‘i’ <= ‘(N/2)-1’ we swap:
    • ‘ARR[i] [j]’ with ‘ARR[j, N-1-i]’
    • ‘ARR[j, N-1-i]’ with ‘ARR[N-1-i, N-1-j]’
    • ‘ARR[N-1-i, N-1-j]’ with ‘ARR[N-1-j,i]’
    • ‘ARR[N-1-j,i]’ with ‘ARR[i][j]’
  4. At the end of these loops, we’ll get rotated matrix.
  5. Print the matrix.
Time Complexity

O(N^2), where ‘N’ is the side length of the given square matrix.

 

As we are traversing the matrix single time.

Space Complexity

O(1).

 

As a constant space is needed because we are doing an in-place rotation.

Code Solution
(100% EXP penalty)
Inplace rotate matrix 90 degree
All tags
Sort by
Search icon

Interview problems

CPP solution

#include <bits/stdc++.h> 
void inplaceRotate(vector<vector<int>> &inputArray)
{
    // Write your code here.
    for(int i=0;i<inputArray.size();i++)
    {
        reverse(inputArray[i].begin(),inputArray[i].end());
    }

    for(int i=0;i<inputArray.size();i++)
    {
        for(int j=i+1;j<inputArray[0].size();j++)
        {
            swap(inputArray[i][j],inputArray[j][i]);
        }
    }
}
7 views
0 replies
0 upvotes

Interview problems

Inplace rotate matrix 90 degree in java

import java.util.*;

import java.io.*;

 

public class Solution {  

    public static void inplaceRotate(int[][] arr, int n) {

        // Write your code here.

 

        for (int i = 0; i < arr.length; i++) {

            for (int j = 0; j < arr.length; j++) {

                //for upper triangular matrix

                if (i >= j) {

                    int temp = arr[i][j];

                    arr[i][j] = arr[j][i];

                    arr[j][i] = temp;

                }

            }

        }

        int k = 0;

        for (int i = arr.length - 1; i >= 0; i--) {

            for (int j = 0; j < arr.length; j++) {

                //for half row only

                if (k <= n/2-1) {

                    int temp = arr[i][j];

                    arr[i][j] = arr[k][j];

                    arr[k][j] = temp;

                }

            }

            k++;

        }

    }

}

111 views
0 replies
0 upvotes

Interview problems

Inplace rotate matrix 90 degree optimize code in C++

#include <bits/stdc++.h> 

using namespace std;

 

void inplaceRotate(vector<vector<int>> &inputArray)

{

    int n = inputArray.size();

 

    // Reverse each row

    for(int i = 0; i < n; i++){

        reverse(inputArray[i].begin(), inputArray[i].end());

    }

 

    // Transpose the matrix

    for(int i = 0; i < n; i++){

        for(int j = i + 1; j < n; j++){

            swap(inputArray[i][j], inputArray[j][i]);

        }

    }

}

 

239 views
0 replies
0 upvotes

Interview problems

Easy python solution

def inplaceRotate(arr, n):

    mat = [[0 for j in range(n)] for i in range(n)]  

    for i in range(n):

        arr[i] = arr[i][::-1]  

    for i in range(n):

        for j in range(n):

            mat[j][i] = arr[i][j]

    

    return mat

44 views
0 replies
0 upvotes

Interview problems

Simple solution

first I transposed the matrix then reverse the rows sequence and you have to check properly how I swaped the rows

43 views
0 replies
0 upvotes

Interview problems

Inplace Roatate array by 90 degree anti-clockwise

#include <bits/stdc++.h> 

void inplaceRotate(vector<vector<int>> &inputArray)

{

    // Write your code here.

    int m = inputArray.size() ;

    vector<vector<int>> ans(m,vector<int>(m));

    

    for(int i=0;i<m;i++)

    {

        for(int j=0;j<m;j++)

        {   

            ans[m-j-1][i] = inputArray[i][j];

        }

    }

 

for(int i=0;i<m;i++)

    {

        for(int j=0;j<m;j++)

        {   

            inputArray[i][j] =  ans[i][j];

        }

    }

}

129 views
0 replies
0 upvotes

Interview problems

Java Solution

import java.util.* ;
import java.io.*; 
public class Solution {
	public static void transpose(int arr[][]){
		int n  = arr.length;
		for(int i = 0; i < n ; i++){
			for(int j = 0; j < n ; j++){
				if(i != j && i < j){
					int temp = arr[i][j];
					arr[i][j] = arr[j][i];
					arr[j][i] = temp;
				}
			}
		}
	}
	
	public static void inplaceRotate(int[][] arr, int n) {
		// Write your code here.
		transpose(arr);
		for(int i = 0; i < n ; i++){
			int j = 0;
			int k = n-1;
			while(j < k){
				int temp = arr[j][i];
				arr[j][i] = arr[k][i];
				arr[k][i] =temp;
				j++;
				k--;
			}
		}
	}

}
115 views
0 replies
0 upvotes

Interview problems

EASY JAVA SOLUTION

import java.util.* ;
import java.io.*; 

public class Solution {
    public static void inplaceRotate(int[][] arr, int n) {
        for (int i = 0; i < n / 2; i++) {
            for (int j = i; j < n - i - 1; j++) {
                int temp = arr[i][j];
                arr[i][j] = arr[j][n - 1 - i];
                arr[j][n - 1 - i] = arr[n - 1 - i][n - 1 - j];
                arr[n - 1 - i][n - 1 - j] = arr[n - 1 - j][i];
                arr[n - 1 - j][i] = temp;
            }
        }
    }
}
59 views
0 replies
0 upvotes

Interview problems

@C++ easy solution beginner friendly :)

void inplaceRotate(vector<vector<int>> &arr)

{

    // Write your code here.

    int n=arr.size();

    int m=arr[0].size();

 

    //Take transpose 

    for(int i=0;i<n;i++)

    {

        for(int j=i+1;j<m;j++){

            swap(arr[i][j],arr[j][i]);

        }

    }

 

    //Reverse each column :)

    for(int i=0;i<n;i++){

 

        int l=0,h=m-1;

        while(l<h){

            swap(arr[l][i],arr[h][i]);

            l++;

            h--;

        }

    }

}

230 views
0 replies
0 upvotes

Interview problems

Easy Solution in C++; please upvote

#include <bits/stdc++.h> 

void inplaceRotate(vector<vector<int>> &inputArray)

{

    // Write your code here.

 

    //make transpose of the matrix

    int n = inputArray.size();

 

    for(int i=0; i<n; i++) {

        for(int j=i+1; j<n; j++) {

            swap(inputArray[i][j], inputArray[j][i]);

        }

    }

 

    for(int i=0; i<n/2; i++) {

        for(int j=0; j<n; j++) {

            swap(inputArray[i][j], inputArray[n-i-1][j]);

        }

    }

}

95 views
0 replies
0 upvotes
Full screen
Console