Binary Search
Find a number in a sorted array, or report that it is missing
DSA, Easy, Binary Search
Which structure or algorithm, and what does it cost.
You get a list nums sorted from smallest to largest, with no repeated values, and a number target. Return the position of target in nums, counting from 0. If target is not in the list, return -1. Your method must stay fast for very long lists.
Examples
Constraints
- 1 <= length of
nums<= 100,000. - All values in
numsare different, sotargetappears at most once. Each value is between -1,000,000,000 and 1,000,000,000. numsis sorted from smallest to largest.- The list is searched many times, so a scan over every item is not accepted.
Your answer must contain
- The simple method and why it is too slow; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(log n) time and O(1) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
The list is sorted. What can one comparison with the middle item tell you about all the other items?
Hint 2 the approach
Compare target with the middle item. One side of the list can never hold target. Drop that side and repeat on the rest.
Hint 3 the key step
Keep two ends of the range that can still hold the target. Check the middle, then move one end past it. Stop when the ends cross.
Walkthrough
Full walkthrough brute force to best
Brute force
Check each item from the left until you find target or reach the end. That is O(n) time and O(1) memory. It ignores that the list is sorted, so a list of 100,000 items can need 100,000 checks for every search.
Best method
Keep a range of positions that can still hold the target, from lo to hi. Look at the middle position. If its value equals the target, you are done. If the value is smaller, the target can only be to the right, so move lo past the middle. If it is larger, move hi before the middle. Each step throws away half of the range, and the sorted order makes that safe: nothing thrown away can hold the target. When lo passes hi, the range is empty, so return -1. This shape, a range that halves, fits any question where one check tells you which side to keep.
Hand trace
Run on [-9, -4, 0, 3, 8, 15] with target 8. Start with lo 0 and hi 5. The middle is position 2, value 0. 0 is smaller than 8, so lo becomes 3. The middle is position 4, value 8. It equals the target, so return 4. That took two checks, where a scan from the left needs five.
Code
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1 # positions that can still hold target
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Time and memory
O(log n) time, because each step halves the range: about 17 steps for 100,000 items. O(1) memory, as only lo, hi and mid are kept.
Common mistakes
- Using
lo < hias the loop test. With one item left,loequalshiand the loop ends before that item is checked. With this style of range, uselo <= hi. - Setting
lo = midorhi = midinstead of moving past the middle. The range can stop shrinking and the loop never ends. - Computing the middle as
lo + hihalved in a language with fixed-size integers. The sum can overflow. Uselo + (hi - lo) // 2there.