TCS Digital Coding Question 1
Cyclically Rotate the array by K
Β
Given an array Arr[ ] of N integers and a positive integer K. The task is to cyclically rotate the array clockwise by K.
Example :
5Β —Value of N
{10, 20, 30, 40, 50}Β —Element of Arr[ ]
2Β —Value of K
Output :Β 40 50 10 20 30
Algorithm :
- Take the value of N, from the user.
- Create a vector of N size.
- Take the elements of the vector from the user.
- Take the value of K , from the user.
- First handle the case : if K >=N, for that set K= K%N.
- Set , K to the position which comes first after the K rotation i.e. K=N-K.
- Now , reverse the vector from 0 To N-K position and again reverse the vector from N-K to N.
- Finally reverse the entire vector to get the desired rotated vector.
C++ Program Based on Above Algorithm :
#include<bits/stdc++.h>
using namespace std;
int main ()
{
int N;
cin >> N;
vector < int >Arr (N);
for (int i = 0; i < N; i++)
cin >> Arr[i];
int K;
cin >> K;
K = K % N; //(if K>=N )
K = (N - K);
reverse (Arr.begin (), Arr.begin () + K);
reverse (Arr.begin () + K, Arr.end ());
reverse (Arr.begin (), Arr.end ());
for (int i = 0; i < N; i++)
cout << Arr[i] << " ";
return 0;
}
Input :
5
10 20 30 40 50
2
Output :
40 50 10 20 30
#Python code Easy Method. #Gangasekhar
arr = [10, 20, 30, 40, 50]
n = 5
k = 2
for i in range(0, n):
k = k % n
result = arr[-k:] + arr[:-k]
print(result)
Kindly join our Discord Channel for technical queries.