33. Search in Rotated Sorted Array

Post by ailswan Aug.27, 2023

33. Search in Rotated Sorted Array

Problem Statement

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

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

Example:

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

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

Input: nums = [1] Output: 0

Solution Approach

The key is to utilize binary search while determining the sorted half of the rotated array to narrow down the search for the target.

Algorithm

  1. Using binary search, identify which half of the rotated array, left or right of the middle, is sorted.
  2. Determine if the target lies within the sorted half’s range and focus the search there, otherwise switch to the opposite half.

Implement

    class Solution:
          def search(self, nums: List[int], target: int) -> int:
              if not nums:
                  return -1
              l, r = 0, len(nums) - 1
              while l <= r:
                  mid = (l + r)// 2
                  if nums[mid] == target:
                      return mid
                  if nums[0] <= nums[mid]:
                      if nums[0] <= target < nums[mid]:  
                          r = mid - 1
                      else:
                          l = mid + 1
                  else:
                      if nums[mid] < target <= nums[len(nums) - 1]:# notice: here is len(nums) - 1
                          l = mid + 1
                      else:
                          r = mid - 1
              return -1