Search in Rotated Sorted Array

MediumBinary search

nums was sorted in ascending order with no repeated values, then rotated: some values from the front were moved to the back, keeping their order. [1, 3, 5, 7, 9] could now be [7, 9, 1, 3, 5].

Given nums and a target, return the index of target in nums, or -1 if it is not there. Aim for O(log n) time.

Examples

Example 1
Input:  nums = [7, 9, 1, 3, 5], target = 3
Output: 3

3 is at index 3.

Example 2
Input:  nums = [7, 9, 1, 3, 5], target = 4
Output: -1

4 is not in the array.

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -10⁴ ≤ nums[i], target ≤ 10⁴
  • All values in nums are different.

Stuck?

Hint 1

Cut the array in the middle. At least one of the two halves is still sorted, and comparing its ends tells you which.

Hint 2

If the target is inside the sorted half’s range, search there; otherwise search the other half.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur