Locate a Value in a Cyclically Shifted Ascending List
Heaps, Sorting & SearchAuto-graded · 27 test casesLast updated
Search a cyclically shifted strictly increasing list of distinct integers for a value in O(log n), returning its index or -1, including unshifted and single-element cases.
Locate a Value in a Cyclically Shifted Ascending List
A list of distinct integers started out in strictly ascending order. It was then cyclically shifted: for some shift amount s with 0 <= s < n, the first s elements were moved to the end while keeping their relative order. In other words, the ascending list [b0, b1, ..., b(n-1)] turned into [bs, b(s+1), ..., b(n-1), b0, ..., b(s-1)]. A shift of s = 0 leaves the list unchanged.
You are given the shifted list nums and an integer target. Return the position of target within nums, or -1 if target does not appear.
Your solution should run in time logarithmic in the length of the list.
Function
Implement search_rotated(nums, target), which takes the shifted list and the value to find and returns a single integer.
Rules
- Positions are 0-based.
- All values in
numsare distinct, so at most one position matches. numsis guaranteed to be a cyclic shift of a strictly ascending list (possibly with shift 0).- Return
-1whentargetis not innums.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- All elements of
numsare distinct.
Examples
Example 1
Input: search_rotated([15, 18, 22, 3, 7, 11], 7)
Output: 4
Example 2
Input: search_rotated([15, 18, 22, 3, 7, 11], 20)
Output: -1
Example 3
Input: search_rotated([1, 4, 9, 12], 12)
Output: 3
Hints
Hint 1
Cut the list at any middle index. The point where values drop can only be on one side, so at least one of the two sides is entirely in ascending order.
Hint 2
Compare the value at the left end of the current window with the value at the middle to decide which side is the ascending one. Use <= so a window where the middle equals the left end is handled correctly.
Hint 3
Once you know the ascending side, check whether target lies between its end values. If yes, keep that side; otherwise discard it and keep the other side. Make sure the endpoint checks are inclusive where the endpoint has not already been ruled out.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A normal binary search needs a fully sorted array, but a cyclically shifted one is only partly ordered. The useful fact is that when you split the current window at mid, the drop in values (the shift point) can lie in only one of the two parts. So at least one part is always in ascending order.
Maintain a window [lo, hi] and repeat:
- Compute
mid. Ifnums[mid] == target, returnmid. - If
nums[lo] <= nums[mid], the left partlo..midis ascending.- If
nums[lo] <= target < nums[mid], the target can only be on the left, so sethi = mid - 1. - Otherwise set
lo = mid + 1.
- If
- Else the right part
mid..hiis ascending.- If
nums[mid] < target <= nums[hi], the target can only be on the right, so setlo = mid + 1. - Otherwise set
hi = mid - 1.
- If
If the window becomes empty, return -1.
Why it is correct
The invariant is: if target is present, its index lies in [lo, hi]. It holds initially. In each step, the ascending part has a known value range given by its endpoints, so a range check tells exactly whether the target can be in it. If the target is within that range it must be in that part (if present at all); if not, it cannot be there and the other part is the only candidate. Since nums[mid] is already ruled out, mid is excluded from the new window. The <= in nums[lo] <= nums[mid] matters when lo == mid (windows of one or two elements): a single-element left part is trivially ascending, and values are distinct so equality happens only in that case. Unshifted lists always take the left-ascending branch, reducing to ordinary binary search.
Complexity
- Time: O(log n), since each iteration halves the window.
- Space: O(1).
Reference solution
def search_rotated(nums: list[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
v = nums[mid]
if v == target:
return mid
if nums[lo] <= v:
# Left part lo..mid is ascending.
if nums[lo] <= target < v:
hi = mid - 1
else:
lo = mid + 1
else:
# Right part mid..hi is ascending.
if v < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1