Skip to content
Concept ยท Data Structures and Algorithms

Binary Search: Algorithm, Python bisect, Off-by-One Bugs and Binary Search on the Answer

Younus FardeenBy Younus FardeenUpdated 1 Dec 202611 min read
Short answer

Binary search finds a target in a sorted array by comparing it with the middle element and discarding the half that cannot contain it, repeating until found or empty. It takes O(log n) time, about 20 comparisons for a million items. It also works on any yes or no condition that flips once, which is binary search on the answer.

On this pageBinary search algorithm, step by stepPython's bisect moduleOff-by-one pitfallsBinary search on the answerSpeed check and practice orderFrequently asked questions

Binary search is easy to describe and surprisingly easy to get wrong. This page gives the standard versions, the standard library shortcut, the bugs that cost people marks in interviews, and then the idea that separates beginners from candidates who solve medium problems: binary search on the answer, with two worked problems.

All code ran on Python 3.9 on 1 December 2026 and the output shown is the real output. The complexity and variant descriptions follow Wikipedia's binary search article and the Python bisect documentation. It assumes you know arrays and have seen Big O.

Binary search algorithm, step by step

Binary search needs sorted data. Look at the middle element. If it equals the target, done. If it is smaller than the target, the target can only be in the right half, so throw the left half away; otherwise throw the right half away. Each step halves the search range, so n items need at most floor(log2 n) + 1 comparisons: 20 for a million items and 30 for a billion.

def binary_search(a, target):
    lo, hi = 0, len(a) - 1                 # search the closed range [lo, hi]
    while lo <= hi:
        mid = lo + (hi - lo) // 2          # same as (lo + hi) // 2 in Python; safe habit in C++/Java
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

nums = [3, 8, 14, 21, 27, 35, 42, 56]
print(binary_search(nums, 27), binary_search(nums, 28), binary_search([], 5))

Output: 4 -1 -1

27 is at index 4, 28 is not present, and an empty list returns -1 without errors. The loop invariant is the key to correctness: at every step, if the target exists, it lies inside the closed range [lo, hi]. Here is the recursive version, which does the same work but uses O(log n) stack space instead of O(1):

def search(a, target, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo > hi:
        return -1
    mid = (lo + hi) // 2
    if a[mid] == target:
        return mid
    if a[mid] < target:
        return search(a, target, mid + 1, hi)
    return search(a, target, lo, mid - 1)

nums = [3, 8, 14, 21, 27, 35, 42, 56]
print(search(nums, 42), search(nums, 4))

# how many steps for a million items?
import math
print(math.floor(math.log2(1_000_000)) + 1, "comparisons at most for 1,000,000 items")

Output:

6 -1
20 comparisons at most for 1,000,000 items
Linear searchBinary search
Needs sorted dataNoYes
TimeO(n)O(log n)
Extra spaceO(1)O(1) iterative, O(log n) recursive
Works on a linked list efficientlyYesNo, it needs O(1) access by index
Best whenSmall or unsorted data, one lookupLarge sorted data, many lookups

Sorting first costs O(n log n) (see sorting algorithms), so for a single lookup in unsorted data, a linear scan is cheaper. Binary search pays off when you search the same sorted data many times.

Python's bisect module

In real code, use bisect. bisect_left(a, x) returns the first index where x could be inserted keeping order, so it points at the first occurrence if x exists. bisect_right returns the index after the last occurrence. Their difference counts duplicates, and insort inserts while keeping the list sorted.

from bisect import bisect_left, bisect_right, insort

a = [1, 2, 2, 2, 5, 9]
print("bisect_left(2) :", bisect_left(a, 2))     # first position where 2 could go
print("bisect_right(2):", bisect_right(a, 2))    # position after the last 2
print("count of 2     :", bisect_right(a, 2) - bisect_left(a, 2))
print("insertion point for 4:", bisect_left(a, 4))
insort(a, 4)
print(a)

def contains(a, x):
    i = bisect_left(a, x)
    return i < len(a) and a[i] == x          # check the bounds, then the value

print(contains(a, 5), contains(a, 6))

# grade table: scores -> letter
cuts, grades = [50, 65, 80], "DCBA"
print([grades[bisect_right(cuts, s)] for s in (35, 50, 79, 80, 95)])

Output:

bisect_left(2) : 1
bisect_right(2): 4
count of 2     : 3
insertion point for 4: 4
[1, 2, 2, 2, 4, 5, 9]
True False
['D', 'C', 'B', 'A', 'A']

Two patterns are worth remembering. A membership test is i = bisect_left(a, x) followed by i < len(a) and a[i] == x: check the bounds first, then the value. And a table lookup, like turning marks into grades, is one bisect_right call over the cut-off list. Note that insort finds the spot in O(log n) but still shifts list items, so it costs O(n). If you need ordered inserts at scale, see binary search tree explained.

Off-by-one pitfalls

  • Infinite loop: writing lo = mid instead of lo = mid + 1 when the loop is while lo < hi. When hi = lo + 1, mid equals lo and nothing changes.
  • Wrong loop condition: while lo < hi and while lo <= hi pair with different range conventions. Closed range [lo, hi] uses <= and hi = mid - 1; half-open [lo, hi) uses < and hi = mid.
  • Overflow in C++ and Java: (lo + hi) / 2 can overflow a 32-bit integer. Use lo + (hi - lo) / 2. Python integers do not overflow, but the habit costs nothing.
  • Unsorted input: binary search returns wrong answers silently, not errors.
  • Duplicates: a plain search returns any matching index. For the first or last occurrence, use the bisect_left or bisect_right logic.
  • Forgetting the not-found case: the answer may be one past the end, so handle i == len(a).

The code below shows the first bug live. A buggy search for the first True in [False, False, False, True] gets stuck at index 2 (cut off after 6 loops so the demo ends), and the half-open version returns the right answer, including 2 as the "none found" index when the list has no True.

# Pitfall 1: infinite loop when lo = mid with lo = mid + 1 forgotten
def first_true_buggy(a):
    lo, hi = 0, len(a) - 1
    steps = 0
    while lo < hi and steps < 6:
        mid = (lo + hi) // 2
        if a[mid]:
            hi = mid
        else:
            lo = mid                         # BUG: should be mid + 1
        steps += 1
    return lo, steps

print("buggy:", first_true_buggy([False, False, False, True]))   # stuck at lo=2 until we cut it off

def first_true(a):
    lo, hi = 0, len(a)                       # half-open [lo, hi): answer may be len(a) = "none"
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid]:
            hi = mid
        else:
            lo = mid + 1
    return lo

print("fixed:", first_true([False, False, False, True]))
print("none true:", first_true([False, False]))

Output:

buggy: (2, 6)
fixed: 3
none true: 2

That second function is the template for the rest of the page: find the first index where a condition becomes true.

Binary search on the answer

You can binary search anything that is monotone: a yes or no test that is false for small values and true for all larger ones, or the other way round. You do not search an array. You search the range of possible answers, test each guess with a helper function, and keep the half that can still contain the best value. The recipe has four steps:

  1. Decide what the answer is (a speed, a capacity, a limit) and its lowest and highest possible value.
  2. Write can(x): is x enough? Check it is monotone.
  3. Search for the smallest x where can(x) is true: lo = mid + 1 when false, hi = mid when true.
  4. The cost is O(log(range) * cost of can).

Worked problem 1: slowest reading speed that still finishes

There are piles of pages and a fixed number of hours. In each hour you read up to k pages from a single pile. Find the smallest k that finishes all piles within the hours. If speed k works, every faster speed works too, so the test is monotone.

# Problem 1: piles of pages, reading speed k pages per hour, you read from one pile in any hour.
# Find the smallest k that finishes everything within the given hours.
from math import ceil

def min_speed(piles, hours):
    def can(k):                              # monotone: if speed k works, any bigger speed works
        return sum(ceil(p / k) for p in piles) <= hours
    lo, hi = 1, max(piles)                   # hi surely works (one pile per hour)
    while lo < hi:
        mid = (lo + hi) // 2
        if can(mid):
            hi = mid                         # mid works, try smaller
        else:
            lo = mid + 1
    return lo

print(min_speed([30, 11, 23, 4, 20], 6))
print(min_speed([3, 6, 7, 11], 8))

Output:

23
4

For piles [30, 11, 23, 4, 20] in 6 hours, speed 23 is the smallest that works. For [3, 6, 7, 11] in 8 hours it is 4. This is a known interview problem (Koko Eating Bananas). The answer range runs from 1 to the biggest pile, so about 5 guesses suffice instead of trying every speed.

Worked problem 2: split into m parts with the smallest largest sum

Split an array of positive numbers into m contiguous parts so that the largest part sum is as small as possible. Guess the limit for the largest part. A greedy pass counts how many parts that limit needs. If it needs m or fewer, the limit is big enough, and every bigger limit is too. The search range is from the biggest single item up to the total sum. The last lines compare it with a brute-force check on the same inputs.

# Problem 2: split the array into m parts so the largest part sum is as small as possible
def split_array(nums, m):
    def parts_needed(limit):                 # greedy: pack as much as possible into each part
        parts, cur = 1, 0
        for x in nums:
            if cur + x > limit:
                parts, cur = parts + 1, 0
            cur += x
        return parts
    lo, hi = max(nums), sum(nums)            # limit cannot be below the biggest item; sum always works
    while lo < hi:
        mid = (lo + hi) // 2
        if parts_needed(mid) <= m:
            hi = mid
        else:
            lo = mid + 1
    return lo

print(split_array([7, 2, 5, 10, 8], 2))
print(split_array([1, 4, 4], 3))
# check against brute force on small inputs
from itertools import combinations
def brute(nums, m):
    n, best = len(nums), float("inf")
    for cuts in combinations(range(1, n), m - 1):
        idx = (0,) + cuts + (n,)
        best = min(best, max(sum(nums[idx[i]:idx[i+1]]) for i in range(m)))
    return best
print(brute([7, 2, 5, 10, 8], 2), brute([1, 4, 4], 3))

Output:

18
4
18 4

[7, 2, 5, 10, 8] into 2 parts gives 18 (7+2+5 and 10+8) and [1, 4, 4] into 3 parts gives 4. The brute force agrees. Other problems of the same shape are minimum capacity to ship packages in D days, aggressive cows (maximise the minimum distance) and painter's partition. For real-valued answers, loop a fixed number of times or until the range is smaller than a tolerance, as in a square-root search that returned 1.414214 for 2.

Speed check and practice order

On Python 3.9 on one laptop, searching a list of 2 million integers for the last item 20 times took about 328 ms with in (a linear scan) and 0.016 ms with bisect_left. Run it and expect different numbers, but the same gap:

# Floating-point answer: square root by binary search on the answer
def sqrt_bs(x, eps=1e-9):
    lo, hi = 0.0, max(1.0, x)
    while hi - lo > eps:
        mid = (lo + hi) / 2
        if mid * mid <= x:
            lo = mid
        else:
            hi = mid
    return lo

print(round(sqrt_bs(2), 6), round(sqrt_bs(0.25), 6))

import time, bisect
a = list(range(2_000_000))
t = time.perf_counter(); [x in a for x in (1_999_999,) * 20]; lin = time.perf_counter() - t
t = time.perf_counter(); [bisect.bisect_left(a, 1_999_999) for _ in range(20)]; bs = time.perf_counter() - t
print("linear scan x20 (ms):", round(lin * 1000), "| bisect x20 (ms):", round(bs * 1000, 3))

Output on that run:

1.414214 0.5
linear scan x20 (ms): 328 | bisect x20 (ms): 0.016

Practice in order: Binary Search, Search Insert Position, First Bad Version, Find First and Last Position of Element in Sorted Array, Search in Rotated Sorted Array, Koko Eating Bananas, Capacity to Ship Packages Within D Days, Split Array Largest Sum. Find them on coding practice websites and see where they sit in DSA interview questions. For a timed plan, use the competitive programming roadmap. Parent path: DSA learning path.

Frequently asked questions

What is binary search?

Binary search is an algorithm that finds a target in a sorted array by repeatedly comparing it with the middle element and discarding the half that cannot contain it. It stops when the target is found or the range is empty, and takes O(log n) time.

What is the time complexity of binary search?

O(log n) in the worst and average case, because the range halves every step; a million items need at most 20 comparisons. Best case is O(1) when the first middle element matches. Space is O(1) for the iterative version and O(log n) for the recursive one.

Does binary search work on unsorted data?

No. It relies on order to decide which half to discard, and on unsorted data it can miss the target without any error. Sort first, which costs O(n log n), or use a linear search if you only need a single lookup.

What is the difference between bisect_left and bisect_right?

Both return an insertion point in a sorted list. For a value that appears several times, bisect_left returns the index of the first occurrence and bisect_right returns the index after the last one. Subtracting them counts the duplicates.

What is binary search on the answer?

It means applying binary search to the range of possible answers instead of to an array. You write a function that checks whether a guess is feasible, relying on feasibility changing only once as the guess grows, and search for the smallest or largest feasible value.

How do I avoid off-by-one errors in binary search?

Pick one convention and keep to it: closed range with lo <= hi and hi = mid - 1, or half-open with lo < hi and hi = mid. Make sure each step shrinks the range, and test with an empty list, one element, and a target outside the range.

Can binary search be used on a linked list?

It works but loses its advantage. Reaching the middle of a linked list takes O(n), so the whole search is O(n) anyway. Binary search needs constant-time access by index, which arrays and Python lists provide.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Array data structure

Indexing, memory layout, measured insert costs, 2D arrays, problems

6 min read
Concept

Sorting algorithms

Bubble vs merge vs quick sort, a complexity table and measured comparisons

9 min read
Concept

Time complexity and Big O

Big O classes, rules for loops and recursion, and real step counts in Python

9 min read