-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotateArrayElemnts.cpp
82 lines (67 loc) · 1.28 KB
/
RotateArrayElemnts.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<bits/stdc++.h>
using namespace std;
void inputElements(vector<int>& v)
{
for(int i=0; i<v.size(); i++)
{
cin>>v[i];
}
cout<<endl;
}
// Brute Approach -> TC - O(N) , SC - O(N)
void rotateArrayLeft(vector<int>& v, int k)
{
int n = v.size();
vector<int> temp(n);
for(int i=0; i<n; i++)
{
temp[i] = v[(i+k)%n];
}
v = temp; // copy into original array
}
// Better Approach -> TC - O(N+K) , SC - O(K)
void rotateArrayLeft(vector<int>&v , int k)
{
int n = v.size();
vector<int> temp(n);
k = k%n;
for(int i=0; i<k; i++)
{
temp[i] = v[i];
}
for(int i=k; i<n; i++)
{
v[i-k] = v[i];
}
int j=0;
for(int i=n-k; i<n; i++)
{
v[i] = temp[j];
j++;
}
}
// Optimal Approach -> TC - O(d) , SC - O(1)
void rotateArrayLeft(int arr[], int n, int k)
{
reverse(arr , arr+k);
reverse(arr+k , arr+n);
reverse(arr , arr+n);
}
int main()
{
int n;
cout<<"size of vector"<<endl;
cin>>n;
vector<int> v(n);
inputElements(v);
int k;
cout<<"Rotate number ";
cin>>k;
rotateArrayLeft(v , k);
cout<<"After Rotation "<<endl;
for(int i=0; i<v.size(); i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}