☰ All problems

Search in Rotated Sorted Array

MediumArrayBinary Search

A logging service writes entries with distinct, increasing IDs into a fixed-size ring buffer. Dumping the buffer from slot 0 gives the IDs in ascending order but possibly rotated, because the oldest entry can sit anywhere in the ring: the IDs [3,8,14,20,31] might come out as [20,31,3,8,14]. Where the rotation happened is unknown, and there may be no rotation at all.

Given the dump nums and an ID target, return the index of target in nums, or -1 if it is not in the dump. The lookup must run in O(log n) time.

Example 1
Input: nums = [20,31,3,8,14], target = 8
Output: 3

Explanation: The ascending run restarts at index 2, and 8 sits right after 3.

Example 2
Input: nums = [20,31,3,8,14], target = 25
Output: -1

Explanation: 25 would fall between 20 and 31, but no such ID was logged.

Example 3
Input: nums = [-4,0,6,11], target = 11
Output: 3

Explanation: This dump is not rotated at all, and the same search still works.

Constraints

  • nums holds between 1 and 5000 IDs.
  • The IDs are distinct integers from -10^4 to 10^4, and target is in the same range.
  • nums is an ascending list 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