Problem : A Sorted Array is rotated by a certain number of elements, find the point of rotation.
Example, For [3,4,5,1,2] , since [1,2] was rotated to the back, point of rotation is 3. And of course, for a sorted array the point of rotation can be assumed 0.
Naive Solution: This is pretty obvious Linear Solution, simply scan the array for a pair a[i] > a[i+1]. If we find it, i is the point of rotation, if there's no such pair, then i = 0 clearly.
Time Complexity : O(n)
Binary Search Variant: Using a variation of Binary Search method, we can find the rotation point in O(logn) steps. At each iteration we compare the middle element of the list with the right (or left) element. For a rotated array, arr[left] > arr[right], so every time we pick a middle element, the point of rotation can lie on either side of mid.
If arr[mid] > arr[right], it means the rotation point is in the second half of the array. So we move left to mid. If arr[mid] <= arr[right] then the rotation point lies in the first half of the array.
Comments
Post a Comment