Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0

Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3

Output: -1

Solution

from typing import List

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums: return -1
        lo = 0
        hi = len(nums) - 1

        while lo <= hi:
            mid = lo + (hi-lo) // 2

            if nums[mid] == target:
                return mid
            elif nums[lo] <= nums[mid]:
                if nums[lo] <= target < nums[mid]:
                    hi = mid - 1
                else:
                    lo = mid + 1
            else:
                if nums[mid] < target <= nums[hi]:
                    lo = mid + 1
                else:
                    hi = mid - 1
        return -1

Test Cases

test = Solution()
assert test.search([4,5,6,7,0,1,2], 0) == 4
assert test.search([4,5,6,7,0,1,2], 3) == -1
assert test.search([4,5,6,7,0,1,2], 4) == 0
assert test.search([4,5,6,7,0,1,2], 5) == 1
assert test.search([4,5,6,7,0,1,2], 6) == 2
assert test.search([4,5,6,7,0,1,2], 7) == 3
assert test.search([4,5,6,7,0,1,2], 0) == 4
assert test.search([4,5,6,7,0,1,2], 1) == 5
assert test.search([4,5,6,7,0,1,2], 2) == 6
assert test.search([1,3,5], 1) == 0
assert test.search([1,3,5], 5) == 2
assert test.search([], 3) == -1
print('All Passed!')

Big O Analysis

Space Complexity: O(1)

Time Complexity: O(log(N))