Responsive Ads Here

Saturday, 13 May 2017

rotate the array for any number of times using a trick

problem id:--https://www.hackerrank.com/challenges/linkedin-practice-array-left-rotation

code:--

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
   int n,d;
    cin>>n>>d;// d is the number of times we want  to rotate the array
    int a[n];
    for(int i=0;i<n;++i)
        cin>>a[i];
// we only need to keep track of the first element after d rotation
// and that will be dth index
//so for any other index we add i
//i.e if we want to find ith index after d rotations then that will be (d+i)%n  index
    for(int i=0;i<n;++i)
        cout<<a[(d+i)%n]<<" ";
    return 0;
}

No comments:

Post a Comment