We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Arrays: Left Rotation
You are viewing a single comment's thread. Return to all 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