Thursday, June 28, 2018

Rotating an array by n

    static int gcd(int a , int b){
        if(b == 0){
            return a;
        } else {
            return gcd(b, a%b);
        }
    }
   
    // Complete the rotLeft function below.
    static int[] rotLeft(int[] a, int d) {
        if(a.length <= 1) {
            return a;
        }
       
        int length = a.length;
       
        for(int i = 0 ; i < gcd(length, d) ; i++) {
            int temp = a[i];
            int j = i;
            while(true) {
                int k = j + d;
                if(k >= length) {
                    k = k - length;
                }
               
                if(k == i) {
                    break;
                }
                a[j] = a[k];
                j=k;
            }
            a[j] = temp;
        }
       
        return a;
    }