SproutStackSproutStack home

Binary Search

6 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

Find the word in a dictionary

Looking up "mango" in a paper dictionary, you don't start at page 1 — you open the middle, see you're in the M's or the T's, and throw away half the book. Repeat ~20 times and you've searched a million pages. That halving instinct is binary search: sorted data lets you discard half the suspects per question.

The template to memorize

def bs(a, t):
    l, r = 0, len(a) - 1
    while l <= r:
        m = l + (r - l) // 2   # overflow-safe midpoint
        if a[m] == t:
            return m
        if a[m] < t:
            l = m + 1          # target lives right
        else:
            r = m - 1          # target lives left
    return -1

Three details interviewers probe: l <= r (not <, or you miss single-element arrays), shrinking to m+1/m−1 (not m, or you loop forever), and the overflow-safe midpoint (a habit from languages where l+r overflows).

A trace

Search for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] (indices 0 to 9):

  • l = 0, r = 9, so m = 4. a[4] = 16 is less than 23, so l = 5.
  • l = 5, r = 9, so m = 7. a[7] = 56 is greater than 23, so r = 6.
  • l = 5, r = 6, so m = 5. a[5] = 23. Found at index 5.

Three questions instead of six comparisons. On a million items the same process needs about 20.

Finding the first occurrence

With duplicates, the basic template returns an index of the target, not necessarily the first. To find the leftmost one, keep searching after a match: record m as a candidate, then continue left with r = m - 1. When the loop ends, the last recorded candidate is the first occurrence. This "lower bound" version also answers "where would this value be inserted to keep the list sorted?", and Python provides it ready-made as bisect.bisect_left.

Beyond searching: search the answer

The real power move: binary search on things that aren't arrays. "Minimum ship capacity to deliver in D days?" — if capacity X works, any bigger X works too (monotonic), so binary search the capacity between max(weight) and sum(weights). Same for "first bad version," "peak element," "koko eating bananas." Whenever yes/no flips exactly once across a range, halve it.

A worked example: ship capacity

Packages weigh [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and must ship in order within 5 days. What is the smallest daily capacity that works?

  • The range. Capacity can be no less than 10, the heaviest package, and never needs to exceed 55, the total.
  • The yes/no check. For a candidate capacity, load packages day by day in order, starting a new day when the next one would not fit, and count the days. If the count is 5 or fewer, the capacity works.
  • The search. Test the middle of the range. If it works, try smaller; if not, try larger.

The search settles on 15: one valid plan is [1–5], [6, 7], [8], [9], [10]. A capacity of 14 needs 6 days. The search needs about 6 checks over a range of 46 values, each check a single pass over the packages.

When it goes wrong

  • The input is not actually sorted, so halving discards the half that held the answer.
  • The yes/no check is not monotonic. If capacity 20 works but 25 does not, there is no single flip point to find, and the search returns nonsense.

Remember this

  • Sorted or monotonic → halve. O(log n) turns millions into ~20 steps.
  • l <= r, exclude m, safe midpoint — the three details that separate passes from fails.

Check your understanding

5 questions · first-try answers earn the most XP

1. What is the time complexity of binary search on a sorted array of n items?
2. Why must the loop condition be `l <= r` rather than `l < r`?
3. Beyond sorted arrays, what makes a problem suitable for binary search on the answer?
4. Why use `l + (r - l) // 2` instead of `(l + r) // 2`?
5. Why must the search move to `m + 1` or `m - 1` rather than `m`?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Practice this pattern elsewhere

More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.