Check Array Rotation

 

You have been given an integer array/list(ARR) of size N. It has been sorted(in increasing order) and then rotated by some number 'K' in the right hand direction.

Your task is to write a function that returns the value of 'K', that means, the index from which the array/list has been rotated.


Sample Input 1:
6
5 6 1 2 3 4
Sample Output 1:
2
Approach 1 - 
package CodingNinjas;

import java.util.Scanner;

public class CheckRotation {

	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		int n=s.nextInt();
		int a[]=new int[n];
		for(int i=0;i<n;i++)
		{
			a[i]=s.nextInt();
		}
		
		int sl=arrayRotateCheck(a);
		System.out.println(sl);

	}
	 public static int arrayRotateCheck(int[] arr) {
		 
		 int l=arr.length;
		 int c=0;
		 for(int i=0;i<l-1;i++)
	 
		 {
			 if(arr[i]>arr[i+1])
			 {
				 c=i+1;
				 break;
			 }
		 }
		 return c;
		 
	}

}
Approach 2 - 
public class Solution {

    public static int arrayRotateCheck(int[] arr){

                int min=Integer.MAX_VALUE;
		int minIndex=0;
		for(int  i=0;i<arr.length;i++)
        {
			if(arr[i] < min && arr.length!=0)
            {
			min=arr[i];
			minIndex=i;
			}
            
		}
		return minIndex;
		
	}
    }

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern