Python coding

Find a value in a rotated sorted list

A list of distinct integers was sorted in increasing order and then rotated: some prefix (possibly empty) was moved to the end, as in [6, 8, 9, 1, 3, 4]. Given that list nums and an integer target, return the index of target, or -1 if it is not there.

nums may be empty. Aim for O(log n): a linear scan misses the point.

  • find_rotated([6,8,9,1,3,4], 3) → 4
  • find_rotated([6,8,9,1,3,4], 8) → 1
  • find_rotated([6,8,9,1,3,4], 5) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Binary search still works: you only need one comparison that tells you which half cannot contain the target.

Hint 2

Whatever mid you pick, one of the two halves is sorted. If nums[lo] <= nums[mid] it is the left one: check whether the target falls in its range, otherwise search the other half.

Hint 3

Try the two-element case [3, 1]: there lo == mid, so the comparison needs <=, and each range check must include the end that is not mid.

Solution and why it works
pythonO(log n) · O(1)
def find_rotated(nums: list[int], target: int) -> int:
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[lo] <= nums[mid]:                  # left half is sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                                      # right half is sorted
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Cut a rotated list anywhere and at least one half is still sorted: compare nums[lo] with nums[mid] to see which. A sorted half tells you in O(1) whether target lies inside its range, so every step drops a half you are sure about. The trap is nums[lo] < nums[mid]: when lo == mid (two elements left) the left half is a single, sorted element and only <= recognizes it; otherwise [3, 1] searching for 1 fails.

Related lab: Loops in motion