Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 7: Linear Search and Binary Search

Linear search is the simplest search there is: check each item in turn until you find the target, or run out of items. It works on any list, sorted or not, and it costs O(n) in the worst case. That sounds slow, and for a huge list it is — but for a short list, or a list you only search once, it is often the right answer. Simplicity is a feature: a linear search has no preconditions, no edge cases to get wrong, and no setup cost.

Binary search is the reward for having sorted data. It looks at the middle item: if the target is smaller, the answer must be in the left half; if larger, in the right half; if equal, you are done. Each step halves the search space, so the cost is O(log n) — on a list of a million items, at most about twenty steps. The code is short, but the details are famously easy to get wrong: the loop condition, the way the bounds move, and the middle calculation all have to be exactly right, or the search misses items or loops forever.

def binary_search(items, target):
    lo, hi = 0, len(items) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


nums = [1, 3, 5, 7, 9, 11, 13]
print(binary_search(nums, 7))   # 3
print(binary_search(nums, 8))   # -1 — not present
print(binary_search(nums, 1))   # 0 — first item
print(binary_search(nums, 13))  # 6 — last item

The standard library already has it

In Python, you rarely write binary search by hand: the bisect module provides it. bisect_left(items, x) returns the position where x would be inserted to keep the list sorted, and bisect_right returns the position after any existing copies. If the item at that position equals x, it is present. bisect is also the tool for maintaining a sorted list as you insert items, and for counting how many values fall below a threshold — both common contest moves. Knowing it exists is half the battle; the other half is recognising when a problem is really a binary search in disguise, which is the subject of the next lesson.

A word of caution about the classic binary search bug: writing mid = (lo + hi) // 2 is fine in Python, but in languages with fixed-size integers the sum can overflow — the safe form is lo + (hi - lo) // 2. In Python the overflow cannot happen, but the habit of writing the safe form is worth building if you ever switch languages. The deeper lesson is that binary search is a pattern, not a recipe: the same halving idea appears in searching, in optimisation, and in guessing games — anywhere you can test a midpoint and discard half the possibilities.

Going further

Binary search has a cousin called exponential search, useful when you do not know how long the list is — for example, when searching an unbounded stream. It starts by checking positions 1, 2, 4, 8, and so on, doubling until it overshoots the target, and then binary searches within the bracket it found. The total cost is still O(log n), and the technique is a good example of the binary search idea applied to a problem where the range itself is unknown. The same doubling trick appears in growing arrays and in network protocols.

Another classic binary search variation is searching a rotated sorted list — a list that was sorted and then cut at some point, such as [4, 5, 6, 1, 2, 3]. One half of the list is always sorted, and by checking which half the middle item belongs to, you can decide which side to search. It is a favourite interview and contest variation because it tests whether you understand the halving idea, rather than having memorised the standard code. The lesson generalises: binary search is a pattern for discarding half the possibilities, not a recipe for one specific function.

Binary search is worth practising until the boundary details feel automatic, because the bugs are always in the same places: the loop condition, the way lo and hi move, and the middle calculation. A good drill is to write the function from memory, then test it on five cases — the target first, the target last, the target in the middle, the target absent and smaller than everything, and the target absent and larger than everything — plus an empty list. If all six pass, the function is very likely correct; if one fails, the failing case tells you exactly which boundary is wrong. Five minutes of drilling now saves an hour of debugging in a contest.

Key Terms

Linear search
Checking each item in turn; O(n), works on any list, sorted or not.
Binary search
Repeatedly halving a sorted list; O(log n), needs the list sorted first.
bisect
The standard-library module for binary search and insertion into sorted lists.
bisect_left
Returns the leftmost position where a value could be inserted while keeping the list sorted.
bisect_right
Returns the rightmost position where a value could be inserted while keeping the list sorted.
Sorted precondition
Binary search only works if the list is sorted; on unsorted data it gives wrong answers.
Off-by-one error
A bug from a boundary being one too high or low — the classic binary search mistake.

Discussion Questions

  1. Why does binary search need the list to be sorted? What goes wrong if you run it on [3, 1, 2] looking for 2?
  2. When is linear search actually the better choice, even though binary search is faster per search?
  3. How would you use bisect to count how many numbers in a sorted list are smaller than 10?

Practice Questions

  1. How many steps does binary search need at most on a sorted list of 1,000,000 items?
  2. What does binary_search return when the target is absent?
  3. Why is the loop condition lo <= hi and not lo < hi?
  4. What does bisect_left([1, 3, 5, 5, 7], 5) return?
  5. You will search the same list a thousand times. Is it worth sorting it first?
Show answers
  1. About 20. Each step halves the list, and 2^20 is about a million, so log2(1,000,000) is just under 20.
  2. -1. The loop ends when lo passes hi, meaning the search space is empty.
  3. Because a single remaining item (lo == hi) still needs checking. With lo < hi the search would miss the case where the target is the last unchecked item.
  4. 2. It returns the leftmost insertion point, before the existing copies of 5.
  5. Yes — sorting once costs O(n log n), then each search is O(log n). A thousand linear searches would cost O(1000n); sorting once plus a thousand binary searches is far cheaper.
Keep reading to complete this lesson