Thursday, 24 August 2017

Left rotation of an array by K steps in JAVA

This is another popular java coding interview question. You can find this question almost every online coding sites like HackerRank, leetcode etc.

We have an array mainArr[]={1,2,3,4,5,6}  and K is given as 3.

So after left rotation, actual array would be mainArr[]={4,5,6,1,2,3}.

Logic: I am using two arrays here. Temp[] array will hold the elements from 0th index to kth index , after that I will merge temp[] and mainArr[] into finalArr[].

Sample code:

/**
 * 
 * @author Sourin
 *
 */
public class LeftRotationOfAnArray {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println("Enter the arrays length: \n");
int n=in.nextInt();
System.out.println("Enter the no of rotation needed.. \n");
int k=in.nextInt();
int mainArr[]=new int[n];
for(int i=0; i<n;i++)
{
mainArr[i]=in.nextInt();
}
int finalArr[]=makeLeftRotation(mainArr,n,k);
for(int m:finalArr)
{
System.out.println("After rotations: "+ m);
}
}
private static int[] makeLeftRotation(int[] mainArr, int n, int k) {
int finalArr[]=new int[n];
int temp[]=new int[k];
int j=0;
for(int l=0;l<k;l++)
{
temp[l]=mainArr[l];
}
for(int i=0;i<n;i++){
if(k<n){
finalArr[i]=mainArr[k];
k=k+1;

}else
{
finalArr[i]=temp[j];
j=j+1;
}
}
return finalArr;
}

}

Sample Output:

Enter the arrays length: 

6
Enter the no of rotation needed.. 

3
1
2
3
4
5
6
After rotations: 4
After rotations: 5
After rotations: 6
After rotations: 1
After rotations: 2
After rotations: 3


4 comments:

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...