Arrays: Left Rotation

  • + 0 comments

    It's easy when you directly read them from system input. Try to make it work on already stored array. That's what problem statement says. It gets tricky and interesting after that to solve it in o(n) without extra memory.

    i.e. // Complete roLeft function

    My solution

    private static int getIncomingIndex(int index, int rotations, int length) {
        if(index < (length - rotations)) {
            return index + rotations;
        }
        return index + rotations - length;
    }
    
    // Complete the rotLeft function below.
        static int[] rotLeft(int[] a, int d) { 
               int rotations = d % a.length;
    
        if(a.length == 0 || a.length == 1 || rotations == 0) {
            return a;
        }
    
        if( a.length % 2 == 0 && a.length / 2 == rotations) {
            for(int i =0 ; i < a.length / 2 ; i++) {
                swap(a, i, i + rotations);
            }
        } else {
            int count = 0;
            int i = 0;
            while(true) {
                int dstIndex = getIncomingIndex(i, rotations, a.length);
                swap(a, i, dstIndex);
                i = dstIndex;
                count++;
                if(count == a.length - 1) {
                    break;
                }
            }
        }
        return a;
    }