Number of rotations
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[][] input = {
null,
{},
{1},
{2,5,6,8,9,10},
{8,9,10,2,5,6},
{10,2,3,5,6,8,9},
{9,10,2,3,5,6,8}
};
for(int i=0;i<input.length;i++){
System.out.println("Input: " + Arrays.toString(input[i]) +
" Result: " + solution.rotations(input[i]));
}
}
public int rotations(int[] input) {
if(input == null || input.length < 2) {
return 0;
}
int start=0;
int end = input.length-1;
while(start <= end) {
if(input[start] <= input[end]){
return start;
}
int mid = start+end/2;
int next = (mid+1)%input.length;
int prev= (mid-1+input.length)%input.length;
if(input[mid] <= input[next] && input[mid] <= input[prev]){
return mid;
}
if(input[mid] > input[start]){
start = mid+1;
} else if(input[mid] < input[end]){
end = mid-1;
}
}
return -1;
}
}