Home » Java programs

Java program for Left Rotation in Array

In this article, we are going to learn what will be the position of array elements after Left rotating d times an array using a very simple and easy trick in just O(n) complexity where n is the size of the array. Where 1<=d<=n.
Submitted by Anamika Gupta, on August 08, 2018

Let’s take an array a[3,4,5,1,0] here we can see after 1 rotation the position of the array element will be a [4,5,1,0,3], after 2 left rotations a[5,1,0,3,4] and so on hence we can see after d rotation the position of the ith element will be (i-d+n)%n.

Because ith element will go back in left side i.e. i-d, which is the position of element from back side so we add n in i-d to get the position from beginning and we take modulo of i-d+n because here the array is in rotation i.e. after every n-1 (that is the last index ), 0 index will come so we have taken modulo to get actual position.

In the above example, you can see after 2 rotation the position of the 0th element is (0-2+5)%5 i.e. 3, hence after 2 rotation the position of the 0th element is at 3rd index.

import java.util.*;

public class Left_rotate
{
	public static void main(String ar[])
	{
		Scanner sc=new Scanner(System.in);
		//number of elements in array
		int n=sc.nextInt();    
		//number of rotation to be performed in the array
		int d=sc.nextInt();  
		int a[]=new int[n];
		
		for(int i=0;i<n;i++)
		{
			int ele=sc.nextInt();
			a[(i-d+n)%n] = ele;
		}
		System.out.println("Array after left rotation");
		for(int i=0;i<n;i++)
			System.out.print(a[i]+" ");
	}
}

Output

    Run 1 (Rotating 6 times)
    6 6
    6 7 4 6 7 8
    Array after left rotation
    6 7 4 6 7 8 

    Run 2 (Rotating 6 times)
    6 2
    6 7 4 6 7 8
    Array after left rotation
    4 6 7 8 6 7 



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.