Find the index of a target value in a sorted array that has been rotated at an unknown pivot.
Problem
You are given a list of distinct integers that was originally sorted in ascending order, then rotated at an unknown pivot. For example, a sorted array like [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2].
Given the rotated array and a target value, return the index of the target if it exists. Otherwise, return -1.
You should aim for a solution that is faster than linear search.
Clarifications
- All numbers are distinct.
- The rotation may be zero, meaning the array may already be sorted.
- If the target appears, return any valid index (there will be at most one because values are distinct).
Input Format
nums: an integer array of distinct valuestarget: an integer value to search for
Output Format
- Return the index of
targetinnums, or-1if it does not exist.
Constraints
1 <= nums.length- Values in
numsare distinct numsis sorted in ascending order and then rotated- A logarithmic-time approach is expected
Example 1
Input
nums = [4,5,6,7,0,1,2], target = 0
Output
4
Explanation
The value 0 is present at index 4.
Example 2
Input
nums = [4,5,6,7,0,1,2], target = 3
Output
-1
Explanation
The value 3 does not appear in the array.
Show 1 more example
Example 3
Input
nums = [1], target = 1
Output
0
Explanation
The only element matches the target.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.