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⁹numsis a list sorted from smallest to largest, rotated by 0 tonums.length - 1places
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Binary Search
- Median of Two Sorted ArraysAI round · Hard
- Find First and Last Position of Element in Sorted ArrayAI round · Medium
- Koko Eating BananasAI round · Medium
- Search Insert PositionEasy
- Search a 2D MatrixMedium