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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
L = 10 | |
lst = [random.randint(0,100) for _ in xrange(L)] | |
lst.sort() | |
K = random.randint(0,L) | |
lst = lst[K:] + lst[:K] # rotate by random K | |
def find_rotation_naive(L): | |
for i in xrange(len(L) - 1): | |
if L[i] > L[i+1]: | |
return i + 1 | |
return 0 |
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_rotation_binary_search(L): | |
left,right = 0,len(L) - 1 | |
while L[left] > L[right]: | |
mid = (left + right) / 2 | |
if L[mid] > L[right]: | |
left = mid + 1 | |
else: | |
right = mid | |
return left |
Comments
Post a Comment