Practice · Binary search · 2 of 5

Search a Rotated Sorted List

A list of different integers was sorted in increasing order and then rotated by some amount (possibly none): some items were moved, in order, from the end to the front, the way [2, 5, 8, 9, 13] can become [9, 13, 2, 5, 8].

Given the rotated list nums and an integer target, return the index of target in nums, or -1 if it isn't there. Your solution should take O(log n) time.

Example 1

Input
nums = [9, 13, 2, 5, 8], target = 5
Output
3

Example 2

Input
nums = [9, 13, 2, 5, 8], target = 10
Output
-1
10 would belong between 9 and 13, and it isn't there.

Constraints

  • nums holds 1 to 5000 numbers, all different.
  • Every number, and target, is between −10⁴ and 10⁴.
  • nums is an increasing list rotated by some amount from 0 to n − 1.