Search in Rotated Sorted Array
Search for a target value in an array of distinct elements rotated at an unknown pivot in O(log n) time by checking which half is sorted.
01The problem
A sorted array of distinct integers was 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]].
Given the rotated array nums and an integer target, return the index of target if it is in nums, or -1 if it is not.
You must write an algorithm with O(log n) runtime complexity.
| Input | Output | Why |
|---|---|---|
nums = [4, 5, 6, 7, 0, 1, 2], target = 0 | 4 | 0 is found at index 4 |
nums = [4, 5, 6, 7, 0, 1, 2], target = 3 | -1 | 3 does not exist in the array |
nums = [1], target = 0 | -1 | Single element array does not contain 0 |
Constraints: 1 to 5,000 distinct values, values between -10,000 and 10,000.
Loading the rest of the lesson…