Find a target’s original position in a distinct sorted array whose starting position may have been rotated.
Problem
Input. An integer list nums obtained by rotating a strictly increasing list, and an integer target.
Output. Return the target’s zero-based index in the supplied rotated list, or -1 if absent.
Rules. Values are distinct, and zero rotation is valid.
Do not sort or otherwise modify the input; returned positions refer to its current order.
Empty input returns -1. Supporting duplicate values is a changed contract below.
Example. For [4, 5, 6, 7, 0, 1, 2] and target 0, return 4.
Target 3 in that list returns -1.
Picture
Reuse the inclusive candidate interval: if the target exists, its index remains in [left,right].
First compare nums[middle] with target. Equality returns immediately, so later tests can exclude the midpoint.
At most one rotation drop exists. If nums[left] <= nums[middle], the left half is sorted; otherwise, the right half is sorted.
| Known sorted half | Target fits when | Retain if it fits |
|---|---|---|
left..middle | nums[left] <= target < nums[middle] | [left,middle-1] |
middle..right | nums[middle] < target <= nums[right] | [middle+1,right] |
If the target does not fit the sorted half, retain the other half. Neither update can discard a possible occurrence.
For [4,5,6,7,0,1,2] and target zero:
| Candidate interval | Probe | Decision |
|---|---|---|
[0,6] | Index 3 has 7 | Sorted values 4 through 7 exclude zero; retain [4,6] |
[4,6] | Index 5 has 1 | Sorted values 0 through 1 include zero; retain [4,4] |
[4,4] | Index 4 has 0 | Return 4 |
Trace L, m, and R mean left, middle, and right.
Problem trace
A sorted half can be discarded when its bounds exclude the target
- L
- 0
- m
- 3
- R
- 6
- L
- 0→4
- m
- 3→5
- sorted
- indices 0..3→indices 4..5
- found
- 5→4
- L
- 4→not shown
- R
- 6→not shown
- Recognize it
- The array was sorted and rotated once with distinct values, so although the whole interval may cross the pivot, at least one side of middle remains sorted.
- Keep true
- If target 0 exists, it remains in inclusive [left, right]. A half is discarded only after its sorted value range proves whether target can occur there.
- Reuse it
- When a monotone ordering is disrupted once, find a locally ordered region and use its endpoint values to make the same safe-elimination argument as ordinary binary search.
Reference drawing
Problem trace
A sorted half can be discarded when its bounds exclude the target
Execution trace
- L
- 0
- m
- 3
- R
- 6
- L
- 0→4
- m
- 3→5
- sorted
- indices 0..3→indices 4..5
- found
- 5→4
- L
- 4→not shown
- R
- 6→not shown
- Recognize it
- The array was sorted and rotated once with distinct values, so although the whole interval may cross the pivot, at least one side of middle remains sorted.
- Keep true
- If target 0 exists, it remains in inclusive [left, right]. A half is discarded only after its sorted value range proves whether target can occur there.
- Reuse it
- When a monotone ordering is disrupted once, find a locally ordered region and use its endpoint values to make the same safe-elimination argument as ordinary binary search.
Code
def search_rotated(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] == target:
return middle
if nums[left] <= nums[middle]:
if nums[left] <= target < nums[middle]:
right = middle - 1
else:
left = middle + 1
elif nums[middle] < target <= nums[right]:
left = middle + 1
else:
right = middle - 1
return -1
Each unsuccessful probe removes its midpoint and roughly half the candidates. Distinct input needs comparisons and auxiliary space.
With duplicates, [1,0,1,1,1] and target zero incorrectly return -1.
Equal left/middle values no longer prove the left half is sorted.
Unlike minimum search, this loop checks midpoint equality before discarding it.
Change Ambiguity or Output
Start from search_rotated. Two adjustable parts are the ordering evidence and the result representation.
-
Permit duplicates.
New task: Return an occurrence in a rotated nondecreasing array, or
-1.Picture and change: Keep the first equality check. If left, middle, and right values agree, the endpoint values are also known nonmatches.
Discard only those endpoints; their equality does not locate the rotation drop.
Code: Complete replacement:
def search_rotated_duplicates(nums, target): left, right = 0, len(nums) - 1 while left <= right: middle = (left + right) // 2 if nums[middle] == target: return middle if nums[left] == nums[middle] == nums[right]: left += 1 right -= 1 elif nums[left] <= nums[middle]: if nums[left] <= target < nums[middle]: right = middle - 1 else: left = middle + 1 elif nums[middle] < target <= nums[right]: left = middle + 1 else: right = middle - 1 return -1Check:
[1,0,1,1,1], target zero, returns index one.[1,1,1], target two, returns-1.No first-occurrence guarantee is added. All-equal absent input can require work; auxiliary space remains .
Use when: Duplicate values remove the evidence needed to discard a complete half.
-
Return membership only.
New task: Report a Boolean rather than an index, under the original distinctness contract.
Picture and change: Keep every search decision. Convert the returned missing sentinel explicitly.
Code: Place this complete wrapper after the retained
search_rotateddefinition.def contains_rotated(nums, target): return search_rotated(nums, target) != -1Check:
[1,2,3], target one, returnsTruedespite its zero index. Empty input returnsFalse.Using
bool(index)would treat index zero as false and missing-1as true.Use when: Only the output representation changes. The reference’s assumptions and complexity remain unchanged.
Rebuild the Evidence
Why does the duplicate variant lose logarithmic worst-case progress?
Answer: Equal boundary and midpoint values may justify removing only two positions, not a half. Correctness survives; halving does not.