100 XP

85. Search a rotated sorted list

Advanced searching

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

Inputnumbers = [15, 18, 22, 3, 7, 9], target = 7
Output4
Explanation7 is at index 4.

Example 2

Inputnumbers = [15, 18, 22, 3, 7, 9], target = 10
Output-1
Explanation10 isn't in the list.

Example 3

Inputnumbers = [5, 1, 3], target = 5
Output0
ExplanationRotated after the 5: it comes first.

Constraints

  • numbers has 0 to 500 different whole numbers: a sorted list, rotated at some point (or not at all).
  • target is a whole number.

Submit also runs 11 more tests you can't see.

Code
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