Rotate Array

 

You have been given a random integer array/list(ARR) of size N. Write a function that rotates the given array/list by D elements(towards the left).

Sample Input 1:
5
2
1 2 3 4 5
Sample Output 1:
Updated Array -> 
3 4 5 1 2 
package CodingNinjas;

import java.util.Scanner;

public class RotateArray {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n=s.nextInt();
		int d=s.nextInt();
		int a[]=new int[n];
		for(int i=0;i<n;i++)
		{
			a[i]=s.nextInt();
		}
		
		rotate(a, d);
		print(a);

	}
	
	public static void print(int a[])
	{
		System.out.println("Updated Array -> ");
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+" ");
		}

	}
	public static void rotate(int[] arr, int d) {
		
		int l=arr.length;
		int t[]=new  int[l];
		int k=0;
		for(int i=0;i<d;i++)
		{
			t[i]=arr[i];
			
		}
		for(int i=d;i<l;i++)
		{
			arr[i-d]=arr[i];
		}
		for(int i=l-d;i<l;i++)
		{
			arr[i]=t[k++];
		}
	}
}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern