AAlgoLoopSpaced repetition for LeetCode
MEDIUMBinary SearchLeetCode ↗

Search in Rotated Sorted Array

The key idea

After a rotation, any split of the array into a left and right half leaves at least one half still sorted. At each step, check which half is sorted, then test whether the target falls inside that sorted half's range to decide which side to discard.

Problem

There is an integer array nums sorted in ascending order with distinct values. Before being passed to your function, nums is possibly rotated at an unknown pivot index k (0 <= k < nums.length), so that the array becomes [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the rotated array nums and an integer target, return the index of target if it is in nums, or -1 if it is not. You must write an algorithm with O(log n) runtime complexity.

Constraints

Examples

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

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems