[40, 50, 60, 10, 20, 30] was sorted, then cut and swapped. Find a value in O(log n).
Predict
[40, 50, 60, 10, 20, 30] was sorted, then cut and swapped. At which index does the moved part start?
The test a[i] < a[0] answers no for the first part and yes for the part that moved:
The rotated list
012345
a
405060102030
a[i] < a[0]?
nononoyesyesyes
The first yes is the start, index 3.
It flips once, so the loop you wrote by hand finds where the original order starts. Then one more binary search, in whichever part can hold the target. Give bisect_left that part's lo and hi, not a slice:
It agreed with list.index on 3,000 random rotations of distinct values.
Repeats break it. In [2, 2, 2, 0, 2] the test answers no, no, no, yes, no, and flips back. With repeats, nothing beats O(n) in the worst case, because the one smaller value can hide anywhere among copies that all look the same.
In the editor, write search_rotated(a, target), the function the code above calls. It searches the rotated list for three values.
Pick an answer above to see the rest
Instructions
1
Write search_rotated(a, target): a held distinct values in order, then was cut and its two parts swapped. Return the index of target, or -1, in O(log n).
2
First binary search for where the moved part starts, the first value below a[0]. Then search only the part that can hold the target, with bisect_left(a, target, lo, hi).