Showing posts with label Array Left rotation. Show all posts
Showing posts with label Array Left rotation. Show all posts

Sunday, June 24, 2018

Rotate Left function in JAVA

Here is an interesting way to solve the problem of Array Left Rotation function:

The left rotation problem as shown on HackerRank:
left rotation operation on an array shifts each of the array's elements  unit to the left. For example, if  left rotations are performed on array , then the array would become .


static int[] rotLeft(int[] a, int d) {
   int[] b = new int[a.length];
   System.arraycopy(a, d, b, 0, (a.length - d));
   System.arraycopy(a, 0, b, (a.length - d), d);
   return b;
}



What happens here is:

  • First, we initialize a new array to hold our shifted values.
  • We then decide where to split the array using the d value, 
  • Then, you copy the old array part by part to the new array and you have a solution.