Search in Rotated Sorted Array

Medium Binary Search AI round

nums is a list of different whole numbers that was sorted from smallest to largest and then rotated: some of its first numbers, perhaps none, were moved from the front to the back, keeping their order. target is a whole number.

Find target in nums.

Return the position of target in nums, counting from 0, or -1 if it is not there.

Example 1

Input: nums = [19,23,31,-8,-5,0,4,7,12], target = 31
Output: 2

The sorted list -8, -5, 0, 4, 7, 12, 19, 23, 31 had its first six numbers moved to the back, so it now starts at 19. 31, the largest number, sits just before the cut, at position 2.

Example 2

Input: nums = [6,9,-2,0], target = 9
Output: 1

Example 3

Input: nums = [10,20,30,40], target = 25
Output: -1

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹, and no number appears twice
  • -10⁹ ≤ target ≤ 10⁹
  • nums is a list sorted from smallest to largest, rotated by 0 to nums.length - 1 places

Watch the explanation

More Binary Search

All Binary Search problems