|
| 1 | +/* |
| 2 | + Problem Statement: |
| 3 | + Given an array, find out how many times it has to been rotated |
| 4 | + from its initial sorted position. |
| 5 | + Input-Output: |
| 6 | + Eg. [11,12,15,18,2,5,6,8] |
| 7 | + It has been rotated: 4 times |
| 8 | + (One rotation means putting the first element to the end) |
| 9 | + Note: The array cannot contain duplicates |
| 10 | +
|
| 11 | + Logic: |
| 12 | + The position of the minimum element will give the number of times the array has been rotated |
| 13 | + from its initial sorted position. |
| 14 | + Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. |
| 15 | + Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N). |
| 16 | + If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]<a[i+1]. |
| 17 | +
|
| 18 | + Some other test cases: |
| 19 | + 1. [1,2,3,4] Number of rotations: 0 or 4(Both valid) |
| 20 | + 2. [15,17,2,3,5] Number of rotations: 3 |
| 21 | +*/ |
| 22 | + |
| 23 | +import java.util.*; |
| 24 | + |
| 25 | +class howManyTimesRotated |
| 26 | +{ |
| 27 | + public static void main(String[] args) |
| 28 | + { |
| 29 | + Scanner sc = new Scanner(System.in); |
| 30 | + int n = sc.nextInt(); |
| 31 | + int[] a = new int[n]; |
| 32 | + for(int i = 0; i < n; i++) |
| 33 | + a[i] = sc.nextInt(); |
| 34 | + |
| 35 | + System.out.println("The array has been rotated "+rotated(a)+" times"); |
| 36 | + sc.close(); |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + public static int rotated(int[] a) |
| 41 | + { |
| 42 | + int low = 0; |
| 43 | + int high = a.length-1; |
| 44 | + int mid=0; // low + (high-low)/2 = (low + high)/2 |
| 45 | + int i=0; |
| 46 | + while(low<=high) |
| 47 | + { |
| 48 | + mid = low + (high-low)/2; |
| 49 | + i++; |
| 50 | + if(a[mid]<a[mid-1] && a[mid]<a[mid+1]) |
| 51 | + { |
| 52 | + break; |
| 53 | + } |
| 54 | + else if(a[mid]>a[mid-1] && a[mid]<a[mid+1]) |
| 55 | + { |
| 56 | + high = mid+1; |
| 57 | + } |
| 58 | + else if(a[mid]>a[mid-1] && a[mid]>a[mid+1]) |
| 59 | + { |
| 60 | + low = mid-1; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return mid; |
| 65 | + } |
| 66 | +} |
0 commit comments