Rotate Array|Coding Problems
Problem Statement:
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.
Code & Algorithm:
/* author : @akash */#include<bits/stdc++.h>
using namespace std;#define ll long long int
#define pb push_back
#define mod 1000000007
#define ld long doublevoid solve()
{
int n,d;
cin>>n>>d;
int a[n];
for(int i=0;i<n;++i)
{
cin>>a[i];
}
for(int i=0;i<d;++i)
{
int tmp=a[0];
for(int j=1;j<n;++j)
{
a[j-1]=a[j];
}
a[n-1]=tmp;
}
for(int i=0;i<n;++i)
{
cout<<a[i]<<" ";
}
}int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--)
{
solve();
cout<<"\n";
}
return 0;
}// time complexity of this algorithm is : T(n)=O(n*d)
Thank You.
Akash Kumar
Software Engineer