The problem, in one line. Given a sorted list of distinct numbers and a target, return the position of the target, or -1 if it is not there. LeetCode 704.
The tell. A list that is already sorted, and a question about where one value sits. Sorted order lets one look at the middle rule out half the list for good.
The wrong first idea
Walk the list from the left and compare each number to the target.
for i, x in enumerate(nums):
if x == target:
return i
return -1
Correct, but it ignores the order. A million numbers can cost a million looks, where halving needs about twenty.
The invariant
This is the same idea the clinic teaches in full: Clinic #11: Binary Search. Keep two ends, lo and hi, around the part of the list that could still hold the target.
flowchart LR A["lo 0, hi 5<br/>mid 2 holds 3<br/>3 < 9, go right"] --> B["lo 3, hi 5<br/>mid 4 holds 9<br/>found, return 4"]
The sentence that stays true every step: if the target is in the list, it is between lo and hi. Each look at the middle throws away a half that cannot hold it, and the middle itself is never kept.
The solution
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # safe middle, no overflow
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1 # mid is ruled out, step past it
else:
hi = mid - 1
return -1
print(search([-1, 0, 3, 5, 9, 12], 9))
print(search([-1, 0, 3, 5, 9, 12], 2))
print(search([5], 5))
4
-1
0
func search(nums []int, target int) int {
lo, hi := 0, len(nums)-1
for lo <= hi {
mid := lo + (hi-lo)/2 // safe middle, no overflow
if nums[mid] == target {
return mid
}
if nums[mid] < target {
lo = mid + 1 // mid is ruled out, step past it
} else {
hi = mid - 1
}
}
return -1
}
Same three calls print 4, -1, 0.
Complexity
- Time O(log n): each loop halves the range, so a million numbers take about twenty loops.
- Space O(1): two indexes and the middle.
Traps
- Writing
lo < hias the loop test. The one-element list[5]with target 5 never gets looked at and returns -1. - Setting
lo = midorhi = mid. On[1, 3]with target 3 the range stops shrinking and the loop never ends. - Using
(lo + hi) / 2in a language with fixed-size integers. On a list with over a billion entries the sum wraps negative, which sat in a famous textbook and a standard library for years.
Next in the ladder
Search Insert Position drops the promise that the target is present. When it is missing, you must say where it would go, and the answer is hiding in where lo ends up.