My method works but apparently for Hackerrank it's not fast enough when dealing with big numbers. How do I optimize it? n is the array size, k is the number of times the array's elements should be rotated left.
public static int[] arrayLeftRotation(int[] a, int n, int k) {
int[] holder = new int[n];
for(int m=0; m<k; m++)
{
for(int b = 0; b<n; b++)
{
if(b==0) holder[n-1]=a[b];
else holder[b-1]=a[b];
}
a = holder;
holder = new int[n];
}
return a;
}
Dequeand remove elements from the head and add it to the tail. If you require an array, then you should probably treat it as circular and have a pointer to the "first" element, and shift the pointer when rotating the array.System#arrayCopyorArrays#copyOfRangecould optimize your method if any of those methods are intrinsic. Otherwise I'd stick with StinePike's answer, as it's only O(n) instead of O(nk).