-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_array.cpp
More file actions
56 lines (50 loc) · 860 Bytes
/
rotate_array.cpp
File metadata and controls
56 lines (50 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <vector>
using namespace std;
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b, a%b);
}
void rotate(vector<int> &arr,int n,int d){
/* time complexity O(n)
spcae complexity O(1)
*/
int i, j, k, temp;
for (i = 0; i < gcd(d, n); i++)
{
temp = arr[i];
j = i;
while(1)
{
k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
int main() {
int t;
cin>>t;
while(t--){
int n,d;
cin>>n;
vector<int> arr(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
cin>>d;
rotate(arr,n,d);
for(int i=0;i<n;++i){
cout<<arr[i]<<" ";
}cout<<endl;
}
return 0;
}