DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Linear foundations · Topic 5 of 18

Binary Search

Look at the middle and throw away the half that can't hold the answer: log n steps instead of n.

Watch in Lens

Spot it

Signals in the question

⌕The data is sorted (or rotated sorted).

⌕You need something in O(log n), or n is huge.

⌕"Find the smallest x that works": a yes/no check that flips once.

The idea

O(log n) time · O(1) space

Keep the range [l, r] that can still hold the answer. Check the middle: if it's too small, the answer is to the right; if too big, to the left. Each check halves the range, so a million items take about 20 checks.

Template · Exact match

1def search(nums, target):2    l, r = 0, len(nums) - 13    while l <= r:4        mid = (l + r) // 25        if nums[mid] == target:6            return mid7        if nums[mid] < target:8            l = mid + 19        else:10            r = mid - 111    return -1

The template, filled in for Binary Search. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchBinary Search, explainedNeetCode · YouTube · free↗¶ReadBinary searchCP-Algorithms · free↗

Practice set

Loading your mission…

Common mistakes

1l < r vs l <= r: decide whether the range is inclusive and stay consistent.

2mid = (l + r) / 2 can overflow in Java/C++; use l + (r − l) / 2.

3Setting l = mid (not mid + 1) and looping forever on two items.

Check yourself

Question 1 of 2

How many checks does binary search need for 1,000,000 sorted numbers, at most?