LeetCode 33. Search in Rotated Sorted Array

Description

https://leetcode.com/problems/search-in-rotated-sorted-array/

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

Explanation

find the rotation point and then do binary search

Python Solution

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if (nums == None or len(nums) == 0):
            return -1
        
        if len(nums) == 1:
            if nums[0] == target:        
                return 0             
            else:
                return -1

        rotate_point = len(nums) - 1 
            
        for i, num in enumerate(nums):
            if num < nums[0]:
                rotate_point = i
                break
                
        if nums[0] == target:        
            return 0        
        elif nums[0] > target:        
            start = rotate_point
            end = len(nums) - 1            
        else:    
            start = 0
            end = rotate_point
                
        while start + 1 < end:
            mid = start + (end - start) // 2
            
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                end = mid
            else:
                start = mid
                        
        if nums[end] == target:
            return end
        elif nums[start] == target:
            return start       
        
        return -1
  • Time complexity: O(N).
  • Space complexity: O(1).

One Thought to “LeetCode 33. Search in Rotated Sorted Array”

Leave a Reply

Your email address will not be published. Required fields are marked *