Algorithms · Binary search
Find Minimum in Rotated Sorted Array
A sorted list was rotated. Find the smallest, fast.
The problem
A sorted list was rotated: [0, 1, 2, 4, 5, 6, 7] became [4, 5, 6, 7, 0, 1, 2]. The numbers are all different. Return the smallest, without looking at every number.
rotated_min([3, 4, 5, 1, 2])→1rotated_min([4, 5, 6, 7, 0, 1, 2])→0Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def rotated_min(nums):take the rotated list smallest = nums[0]start with the first number for x in nums:look at every number if x < smallest:smaller? smallest = xremember it return smallestthe smallestNow ask: what if there were a billion?
Logs that wrap around (a ring buffer that overwrites its oldest entries) are rotated sorted lists. Finding the oldest entry among millions is this puzzle.
Aim for O(log n)🔥 boss
Think it through
Picture [4, 5, 6, 7, 0, 1, 2]. Where is the smallest?
- At the start
- Right after the drop
Show the answer
Right after the drop. It climbs, drops once, then climbs again. The smallest is just after the drop, so the job is finding the drop.
The middle is bigger than the last number. Where is the drop?
- To the right of the middle
- To the left of the middle
Show the answer
To the right of the middle. If the middle were in the second climb it would be smaller than the end. Bigger means the drop is still ahead. One comparison halves the search, like ordinary binary search.
Stuck? 3 nudges, smallest first
- Draw it: the numbers climb, drop suddenly, then climb again. The smallest is right after the drop.
- Compare the middle with the right end. If the middle is bigger, the drop must be to the right of the middle.
- While
lo < hi: ifnums[mid] > nums[hi],lo = mid + 1, elsehi = mid. Returnnums[lo].
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def rotated_min(nums):take the rotated list lo, hi = 0, len(nums) - 1the smallest is somewhere in here while lo < hi:until one number is left mid = (lo + hi) // 2look in the middle if nums[mid] > nums[hi]:middle bigger than the right end? lo = mid + 1the drop (and the smallest) is to the right else:the right part is in order hi = midso the smallest is here or to the left return nums[lo]the smallestSolve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.