DEV Community

Ajay k
Ajay k

Posted on

Left Rotate The Array

Today let's see how to left rotate the array

This left rotate question can have say to rotate 1 digit to left or n digit to left lets see both in this post

  1. Left Rotate By 1 Digit
  2. Left Rotate by N Digit

Bonus:- lets look into collections built-in rotate for right and left rotate

lets see left rotate by 1 Digit

int[] reverseTheArrayByOne(int[] arr) {
    int temp = arr[0];
    for (int i = 1; i < arr.length; i++) {
      arr[i - 1] = arr[i];
    }

    arr[arr.length - 1] = temp;
    return arr;
  }
Enter fullscreen mode Exit fullscreen mode

Since we are going to move only one digit we can store the first digit in temp and moving the rest of the elements towards left and we will add the temp to the last index.

Lets see N rotate

We can simply perform N rotate by running the rotate 1 digit N times to get the answer

int[] reverseTheArrayByNTimesEasy(int[] arr, int digits) {
    for (int i = 0; i < digits; i++) {
      arr = reverseTheArrayByOne(arr);
    }
    return arr;
  }

Enter fullscreen mode Exit fullscreen mode

or we can use this method

int[] reverseTheArrayByNDigits(int[] arr, int digits) {
    int[] temp = new int[digits];
    for(int i=0;i<digits;i++){
      temp[i]=arr[i];
    }
    for(int i=0;i<arr.length-digits;i++){
        arr[i]=arr[digits+i];
    }
    for(int i=0;i<temp.length;i++){
        arr[digits-1+i]=temp[i];
    }
    return arr;
  }
Enter fullscreen mode Exit fullscreen mode

To rotate N digits we can make use of temp array to store the N digits and move the remaining digits to the beginning and copy the temp array to the last

Bonus :- we can simply use collections rotate method to perform this array Rotate

int n = 1; 
int[] arr = {2, 5, 8, 9, 12};
    List<Integer> arrList = 
Arrays.stream(arr).mapToObj((e) -> Integer.valueOf(e)).collect(Collectors.toList());
    Collections.rotate(arrList,n);
    System.out.println(arrList.toString());
Enter fullscreen mode Exit fullscreen mode

Here n is the number of digits to be rotated, by default Collections.rotate will perform right rotate to if you want left rotate means you can give negative value.

Collections.rotate(arrList, 1) will perform Right Rotate
Collections.rotate(arrList,-1) Will Perform Left Rotate

Top comments (0)