85. Search a rotated sorted list
A sorted list has been rotated: cut at some point and its two pieces swapped. [3, 7, 9, 15, 18, 22] cut after the
9 becomes [15, 18, 22, 3, 7, 9]. It may also not be rotated at all.
Write a function search_rotated(numbers, target) that takes such a list of different whole numbers and a whole
number target, and returns the index of target in the list, or -1 if it isn't there.
Use binary search, not .index(), in or a loop over every item: the list could be long. Plain binary search fails
here, since the list isn't in order as a whole. But cut it at its middle, and one of the two halves always is.
Example 1
numbers = [15, 18, 22, 3, 7, 9], target = 74Example 2
numbers = [15, 18, 22, 3, 7, 9], target = 10-1Example 3
numbers = [5, 1, 3], target = 50Constraints
numbershas 0 to 500 different whole numbers: a sorted list, rotated at some point (or not at all).targetis a whole number.
Submit also runs 11 more tests you can't see.
- Search as usual with
low,highandmid, returningmidwhennumbers[mid] == target. - Otherwise one half is in order: the left half is when
numbers[low] <= numbers[mid], else the right half is. - If the target lies within the sorted half's range, for the left half
numbers[low] <= target < numbers[mid], search that half. Otherwise it can only be in the other one.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def search_rotated(numbers, target):
"""Find target in a sorted list that was rotated.
numbers: list of int, different values, sorted then
rotated
target: int, the number to look for
Returns: int, the index of target, or -1 if it isn't
in the list
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.