Search a rotated list

A sorted list of different numbers was rotated: its front part was moved to the back, like 4 5 6 7 0 1 2.

What to build

A program that finds a target in a rotated sorted list in O(log n).

Requirements

  • Print the position of the target, or -1 if it is not there.
  • Use binary search, not a scan.

Input

The first line has n and target. The second line has the n different numbers.

Output

The position (from 0), or -1.

Constraints

1 ≤ n ≤ 10⁵.

Example

Input:

7 0
4 5 6 7 0 1 2

Output:

4

Why it works

Cutting a rotated sorted list at the middle always leaves at least one sorted half. Checking whether the target is within the sorted half tells us which half can hold it, so the range halves each step.

Examples

Example 1 · Input
7 0
4 5 6 7 0 1 2
Expected output
4
Example 2 · Input
7 3
4 5 6 7 0 1 2
Expected output
-1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

At every step one half of the range is sorted. Compare nums[low] with nums[mid] to see which.

Hint 2

If the target lies inside the sorted half, search that half; otherwise search the other one.

Hint 3

The numbers are all different. Print -1 if the target is missing.

Solution

Show one correct solution (try it yourself first)
n, target = map(int, input().split())
nums = list(map(int, input().split()))
low, high = 0, n - 1
answer = -1
while low <= high:
    mid = (low + high) // 2
    if nums[mid] == target:
        answer = mid
        break
    if nums[low] <= nums[mid]:
        if nums[low] <= target < nums[mid]:
            high = mid - 1
        else:
            low = mid + 1
    else:
        if nums[mid] < target <= nums[high]:
            low = mid + 1
        else:
            high = mid - 1
print(answer)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Binary search patterns →