Find the Boundary: The Smallest Value in a Rotated List
The radio playlist from the last lesson, [40, 50, 60, 10, 20, 30], has a question hidden in it: where does the wrap happen, and what is the smallest track number? You could scan every item. But there is a yes-or-no question whose answer flips exactly once along the list, and any such flip can be found by binary search.
The rule
When yes-or-no flips only once, shrink toward the first yes.
Many problems hide a list of answers shaped like no, no, no, yes, yes, yes: every position gives "no" up to some point and "yes" after it. The answer you want is the first yes. One template finds it, and it is the most reusable piece of code in this section:
def first_true(lo, hi, is_ok):
while lo < hi:
mid = (lo + hi) // 2
if is_ok(mid):
hi = mid # mid might be the first yes: keep it
else:
lo = mid + 1 # mid is a no: drop it and everything before it
return loIt differs from the classic search in two ways, both deliberate. hi = mid keeps mid in the window, because a yes might be the first one. And the loop runs while lo < hi, stopping when the window is a single position: the answer. Since mid is always less than hi, every step shrinks the window, so it cannot get stuck.
For the rotated list, the question is "is this value no bigger than the last value?" Everything before the wrap is larger than the last item; everything from the smallest value onwards is not. So the first yes is the smallest value:
def rotation_min(nums):
i = first_true(0, len(nums) - 1, lambda i: nums[i] <= nums[-1])
return nums[i]