Learn DSA
Depth-First Search
Greedy Algorithms
Binary Search
Search in Rotated Sorted Array
medium
DESCRIPTION (credit Leetcode.com)
You are given a sorted array that has been rotated at an unknown pivot point, along with a target value. Develop an algorithm to locate the index of the target value in the array. If the target is not present, return -1. The algorithm should have a time complexity of O(log n).
Note:
- The array was originally sorted in ascending order before being rotated.
- The rotation could be at any index, including 0 (no rotation).
- You may assume there are no duplicate elements in the array.
Example 1:
Input:
Output: 4 (The index of 0 in the array)
Example 2:
Input:
Output: -1 (3 is not in the array)
Explanation
Reducing the Search Space
Determining the Sorted Half
Algorithm
- Initialize pointer mid = (left + right) // 2, and check if nums[mid] == target. If we find the target, we return mid. If it isn't, this removes mid from our search space.
- Set mid = (left + right) // 2 and check if nums[mid] == target.
- Check which half is sorted: nums[left] (17) is greater than nums[mid] (1), so the right half is sorted.
- Check if the target is within nums[mid] (1) and nums[right] (3). It is, so we update left = mid + 1 to discard the left half of the array.
Solution
def search(nums, target):left = 0right = len(nums) - 1while left <= right:mid = (left + right) // 2if nums[mid] == target:return midif nums[left] <= nums[mid]:# left half is sortedif nums[left] <= target and target < nums[mid]:# target is in the left halfright = mid - 1else:# target is in the right halfleft = mid + 1else:# right half is sortedif nums[mid] < target and target <= nums[right]:# target is in the right halfleft = mid + 1else:# target is in the left halfright = mid - 1return -1
search for 3 in rotated sorted array
0 / 9
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(log n) where n
is the number of elements in the array. We are reducing the search space by half in each iteration, just like we do in classic binary search.
Space Complexity: O(1) We are using a constant amount of space.
Login to track your progress
Your account is free and you can post anonymously if you choose.