← Whiteboard questions

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

Input nums = [-9, -4, 0, 3, 8, 15], target = 8
Output 4
Why 8 is at position 4.
Input nums = [-9, -4, 0, 3, 8, 15], target = 1
Output -1
Why 1 would sit between 0 and 3, but it is not in the list.
Input nums = [5], target = 5
Output 0
Why Edge case: a list with one item. The same code must handle it with no special branch.

Constraints

Your answer must contain

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 -1

Time 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 < hi as the loop test. With one item left, lo equals hi and the loop ends before that item is checked. With this style of range, use lo <= hi.
  • Setting lo = mid or hi = mid instead of moving past the middle. The range can stop shrinking and the loop never ends.
  • Computing the middle as lo + hi halved in a language with fixed-size integers. The sum can overflow. Use lo + (hi - lo) // 2 there.

Related problems

More Binary Search problems
Binary Search: hints, walkthrough and Python solution