☰ All problems

28. Search in Rotated Sorted Array

MediumArrayBinary Search

An array of distinct integers was sorted in ascending order and then possibly rotated: some prefix was cut off and moved to the end. For example, [3,7,9,15,18,22] rotated after its third element becomes [15,18,22,3,7,9]. The rotation point is unknown (and there may be no rotation at all).

Given the rotated array nums and an integer target, return the index of target in nums, or -1 if it is not present. Aim for O(log n) time.

Example 1
Input: nums = [15,18,22,3,7,9], target = 7
Output: 4
Example 2
Input: nums = [15,18,22,3,7,9], target = 10
Output: -1
Example 3
Input: nums = [8], target = 8
Output: 0

Constraints

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i], target <= 10^4
  • All values in nums are distinct
  • nums is an ascending array that may have been rotated
💡 Hint 1

Split the array at any index mid. At least one of the two halves is sorted normally. How can you tell which one?

💡 Hint 2

If nums[lo] <= nums[mid], the left half is sorted. Then it is easy to check whether target lies inside its value range.

💡 Hint 3

Keep the half that could contain the target and discard the other, exactly like ordinary binary search.

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
function search(nums, target) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc