Given an array of integers rotate the array by k times
INPUT
7 3
1 2 3 4 5 6 7
6 3
1 2 3 4 5 6
12 4
1 2 3 4 5 6 7 8 9 10 11 12
OTPUT
5 6 7 1 2 3 4
4 5 6 1 2 3
9 10 11 12 1 2 3 4 5 6 7 8
Brute force approach:
A simple approach is to use two pointer one start for i=0 and other pointer start from i=i+k
simply swap the both number and once again iterate form i+k to n and simply assign the value of i=0 to i=k in an array.
#include<bits/stdc++.h>
using namespace std;
void rotate(vector<int>& nums, int k) {
int i=0;
k=k%nums.size();
int j=nums.size()-k;
vector<int>kk;
kk=nums;
int c=0;
while(i<k&&j<nums.size())
{
swap(nums[i],nums[j]);
i++;
j++;
c++;
}
for(int i=0;i<nums.size()-c;i++)
{
nums[i+k]=kk[i];
}
}
int main()
{
int n,k;
cin>>n>>k;
vector<int>v;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
v.push_back(x);
}
rotate(v,k);
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
}
TIME COMPLEXITY-O(N)
SPACE COMPLEXITY-O(N)
How can we Optimise the space?
1.we will first reverse the array
2. we will reverse the first k element
3.we will reverse the remaining element from i+k to n
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void rotate(vector<int>& nums, int k) {
int i=0;
k=k%nums.size();
int j=nums.size()-k;
vector<int>kk;
kk=nums;
int c=0;
while(i<k&&j<nums.size())
{
i++;
j++;
c++;
}
reverse(nums.begin(),nums.end());
reverse(nums.begin(),nums.begin()+k);
reverse(nums.begin()+k,nums.end());
// reverse(nums.begin()+k+1,nums.end());
}
int main()
{
int n,k;
cin>>n>>k;
vector<int>v;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
v.push_back(x);
}
rotate(v,k);
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
}
TIME COMPLEXITY:-O(N)
SPACE COMPLEXITY:-O(1)
3.solution using juggling algorithm in the next blog😀😊
if you have any query do feel free to ask in comments