Consider we have an array sorted in ascending order, and that is rotated at some pivot unknown to you beforehand. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. We have given a target value to the search. If we can get it in the array, then return its index, otherwise return -1. We can assume no duplicate exists in the array. So if the array is like [4,5,6,7,0,1,2], then the output will be 4. as the index of this element is present at index 4.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def search(self, nums, target): low = 0 high = len(nums) while low<high: mid = low + (high-low)//2 if nums[mid] == target: return mid if nums[low]<=nums[mid]: if target >=nums[low] and target <nums[mid]: high = mid else: low = mid+1 else: if target<=nums[high-1] and target>nums[mid]: low = mid+1 else: high = mid return -1 ob1 = Solution() print(ob1.search([4,5,6,7,8,0,1,2], 0))