I came across this question in one Interview. Please help me in getting the solution.
Question is:
You have sorted rotatable array, i. e. the array contains elements which are sorted and it can be rotated circularly, like if the elements in array are [5,6,10,19,20,29] then rotating first time array becomes [29,5,6,10,19,20] and on second time it becomes [20,29,5,6,10,19] and so on.
So you need to find the smallest element in the array at any point. You won’t be provided with number times array is rotated. Just given the rotated array elements and find out the smallest among them. In this case output should be 5.
Method 1:
You can do this in
O(logN)time.Use a modified binary search to find the point of rotation which is an index
isuch thatarr[i] > arr[i+1].Example:
The two sub-arrays
(arr[1], arr[2], .., arr[i])and(arr[i+1], arr[i+2], ..., arr[n])are sorted.The answer is
min(arr[1], arr[i+1])Method 2:
When you split the sorted, rotated array into two halves
(arr[1],..,arr[mid])and(arr[mid+1],..,arr[n]), one of them is always sorted and the other always has the min. We can directly use a modified binary search to keep searching in the unsorted half