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 :

How to rotate?
#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

16 comments on “TCS Digital Coding Question 1”