Rotate Array Clockwise (Right To Left)

Prashant | Fri, 12 Jun, 2020 | 494

Rotate array clock wise

Rotating array clock or anti-clock wise is a most commonly asked question in many placements rounds and competitive programing as many of the students use old procedure so they are not selected so just stay with us to learn with fun.

Question:- 

Given an unsorted array arr[] of size N, rotate it by D elements (clockwise). 

Input:
The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements.

Output:
For each testcase, in a new line, output the rotated array.

Constraints:
1 <= T <= 200
1 <= N <= 107
1 <= D <= N
0 <= arr[i] <= 105

Example:
Input:
2
5 2
1 2 3 4 5 
10 3
2 4 6 8 10 12 14 16 18 20

Output:
3 4 5 1 2
8 10 12 14 16 18 20 2 4 6

Explanation :
Testcase 1: 1 2 3 4 5  when rotated by 2 elements, it becomes 3 4 5 1 2.

for the above example lets see and check how it goes :- 

round 1 :- 1 2 3 4 5 - > 2 3 4 5 1

round 2 :- 3 4 5 1 2

So here we were asked to rotate it two times, so we rotated it.

Best optimal solution

using reverse method

//using reverse 
#include<vector>
#include<algorithm>
using namespace std;

int main() {
	//code
	int t;
	cin>>t;
	while(t--){
	    int n,r,num;
	    cin>>n>>r;
	    
	    r=r%n; // if array is rotated more than its size answer will be same
	    int arr[n];
	    for(int i=0;i<n;i++){
	        cin>>arr[i];
	    }
	    //left rotate
	    reverse(arr,arr+r);
	    reverse(arr+r,arr+n);
	    reverse(arr,arr+n);
	    
	    for(int i=0;i<n;i++)cout<<arr[i]<<" ";
	    cout<<endl;
	}
	return 0;
}

using rotate method and vector in C++

#include<vector>
#include<algorithm>
using namespace std;

int main() {
	//code
	int t;
	cin>>t;
	while(t--){
	    int n,r,num;
	    cin>>n>>r;
	    
	    r=r%n;
	    vector<int >arr;
	    for(int i=0;i<n;i++){
	        cin>>num;
	        arr.push_back(num);
	    }
	    rotate(arr.begin(),arr.begin()+r,arr.end());
	    for(auto i : arr)cout<<i<<" ";
	    cout<<endl;
	}
	return 0;
}

Using another array to store value :- 

#include<bits/stdc++.h>
using namespace std;
int main() {
	int t;
	cin>>t;
	while(t--){
	    int n,r;
	    cin>>n>>r;
	    int arr[n],tarr[n];
	    for(int i=0;i<n;i++)cin>>arr[i];
	    for(int i=0;i<n;i++){
	        tarr[i]=arr[(i+r)%n];
	    }
	    for(int i=0;i<n;i++)cout<<tarr[i]<<" ";
	    cout<<endl;
	}
	return 0;
}

 

0 comments
Leave a comment