#include<bits/stdc++.h>
// #include<leetcode.h>
#define null NULL
#define endl '\n'
#define ll long long
using namespace std;
#define goF(i, a, b) for(int i=a; i<b; i++)
#define goB(i, a, b) for(int i=a; i>=b; i--)
/*
*For Forward Shifting: Reverse K elements from the FRONT
*For Backward Shifting: Reverse K elements from the BACK
*/
//TC: O(N), SC:O(1)
void reverse(vector<int>& nums, int start, int end){
while(start <= end){
swap(nums[start++], nums[end--]);
}
}
void fwdShift(vector<int>& nums, int k){
int n = nums.size();
k %= n;
//reverse(nums, 0, n-1);
reverse(nums.begin(), nums.end());
//*Reverse K elements from the FRONT
//reverse(nums, 0, k-1);
reverse(nums.begin(), nums.begin()+k);
//reverse(nums, k, n-1);
reverse(nums.begin()+k, nums.end());
}
void bckwdShift(vector<int>& nums, int k){
int n = nums.size();
k %= n;
//reverse(nums, 0, n-1);
reverse(nums.begin(), nums.end());
//*Reverse K elements from the BACK
//reverse(nums, n-k, n-1);
reverse(nums.begin()+n-k, nums.end());
//reverse(nums, 0, n-k-1);
reverse(nums.begin(), nums.begin()+n-k);
}
class Solution{
private:
void reverse(vector<int>& nums, int start, int end){
while(start <= end){
swap(nums[start++], nums[end--]);
}
}
public:
void rotate(vector<int>& nums, int k){//fwd shifting
int n = nums.size();
k %= n;
reverse(nums, 0, n-1);
//reverse(nums.begin(), nums.end());
//*Reverse K elements from the FRONT
reverse(nums, 0, k-1);
//reverse(nums.begin(), nums.begin()+k);
reverse(nums, k, n-1);
//reverse(nums.begin()+k, nums.end());
}
};
int main(){
vector<int> nums1 = {1, 2, 3, 4, 5, 6, 7};
vector<int> nums2 = nums1;
int k = 1;
fwdShift(nums1, k);
for(int x: nums1) cout<<x<<" ";
cout<<endl;
k = 6;
bckwdShift(nums2, k);
for(int x: nums2) cout<<x<<" ";
cout<<endl;
cout<<"\nGo Google!"<<endl;
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KLy8gI2luY2x1ZGU8bGVldGNvZGUuaD4KI2RlZmluZSBudW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