01 / 20

Binary Search
& bisect

Master the divide-and-conquer search strategy and Python's built-in bisect module to find elements in \( O(\log n) \) time.

Python

What Does "Searching" Mean?

Given a collection of items, searching is the process of finding whether a target value exists and, if so, where it is located. The simplest approach: check every item one by one.

Linear Search
Scan from index 0 to \( n - 1 \). Works on any list, sorted or not.
Binary Search
Repeatedly halve the search space. Requires the list to be sorted.

The Core Idea: Halving the Search Space

Imagine a sorted list. Pick the middle element. If it equals the target, you're done. If the target is smaller, discard the right half. If larger, discard the left half. Repeat until found or the range is empty.

2 5 8 12 17 23 31 44 56 lo mid hi mid = 17 target = 31 > 17 → discard left half, search right

Why \( O(\log n) \) Matters

Each step halves the remaining elements. After \( k \) steps the search space shrinks to \( \frac{n}{2^k} \). The search ends when \( \frac{n}{2^k} = 1 \), giving \( k = \log_2 n \).

n (list size) steps O(n) O(log n) 0 500k 1M

The Binary Search Algorithm

1
Initialise pointers: set lo = 0 and hi = len(arr) - 1.
2
Loop while \( \text{lo} \le \text{hi} \).
3
Compute midpoint: mid = (lo + hi) // 2.
4
If arr[mid] == target, return mid.
5
If \( \text{arr[mid]} < \text{target} \), set lo = mid + 1. Otherwise, set hi = mid - 1.
6
If loop ends without returning, the target is not in the list: return \(-1\).

Binary Search in Python

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

Flowchart: One Iteration

\( \text{lo} \le \text{hi ?} \)
Yes
\( \text{mid} = (\text{lo}+\text{hi})//2 \)
\( \text{arr[mid]}==\text{target?} \)
Yes return mid No
\( \text{arr[mid]}<\text{target?} \)
Yes
\( \text{lo}=\text{mid}+1 \)
No
\( \text{hi}=\text{mid}-1 \)
No return -1

Linear vs Binary Search

Linear Search Binary Search
Time Complexity \( O(n) \) \( O(\log n) \)
Requires Sorted? No Yes
Space \( O(1) \) \( O(1) \) iterative
Best For Small / unsorted lists Large sorted lists
Implementation Simple loop Pointer logic

Python's bisect Module

Instead of writing binary search from scratch, Python's standard library provides the bisect module. It finds the insertion point for a value in a sorted list: the index where the value would go to keep the list sorted.

import bisect nums = [2, 5, 8, 12, 17, 23, 31] bisect.bisect_left(nums, 12) # 3 (index of 12) bisect.bisect_right(nums, 12) # 4 (index after 12) bisect.insort(nums, 15) # inserts 15 in place

bisect_left vs bisect_right

3 7 7 7 12 18 0 1 2 3 4 5 bisect_left = 1 insert before first 7 bisect_right = 4 insert after last 7
bisect_left(a, x)
Returns the leftmost position where x can be inserted. If x exists, points to the first occurrence.
bisect_right(a, x)
Returns the rightmost position. If x exists, points one past the last occurrence.

How to Apply Binary Search

1
Confirm the data is sorted. If not, sort it first or use linear search.
2
Choose your tool: hand-coded binary search for exact-match, or bisect for insertion-point tasks.
3
Set boundaries carefully: inclusive lo, inclusive hi for manual; bisect handles this internally.
4
Handle "not found": manual returns \(-1\); with bisect, check if the index is in bounds and the value matches.
5
Test edge cases: empty list, target smaller than all elements, target larger than all elements, duplicates.

Example 1: Finding a Value

Search for 23 in [2, 5, 8, 12, 17, 23, 31, 44, 56].

Step 1 Step 2 Step 3 2 5 8 12 17 23 31 44 56 23>17 → right 23 31 44 56 23<31 → left 23 ✓ Found at index 5

Example 2: Using bisect for Lookup

Use bisect_left to check if a value exists, then use insort to add a new value.

import bisect scores = [55, 70, 80, 85, 92] # Check if 80 is in the list i = bisect.bisect_left(scores, 80) if i < len(scores) and scores[i] == 80: print("Found 80 at index", i) # index 2 # Insert 78 while keeping sorted order bisect.insort(scores, 78) print(scores) # [55, 70, 78, 80, 85, 92]

Example 3: Counting Duplicates

How many times does 7 appear in [1, 3, 7, 7, 7, 9, 12]? Use both bisect functions:

import bisect arr = [1, 3, 7, 7, 7, 9, 12] left = bisect.bisect_left(arr, 7) # 2 right = bisect.bisect_right(arr, 7) # 5 count = right - left # 3 occurrences

Common Mistakes

✕ Unsorted Input
Binary search only works on sorted data. Using it on an unsorted list gives wrong results silently.
✕ Off-by-One Bounds
Using lo < hi instead of lo <= hi can skip the last element. Be precise with your loop condition.
✕ Wrong Mid Update
Setting lo = mid instead of lo = mid + 1 can cause an infinite loop when lo and hi are adjacent.
✕ Forgetting Bounds Check
With bisect, the returned index can equal len(arr). Always check i < len(arr) before accessing arr[i].
✕ Mixing left and right
Using bisect_right when you want the first occurrence gives index after the target: wrong for lookups.

Summary: bisect Functions

Function Returns Time Use Case
bisect_left(a, x) Leftmost insertion index \( O(\log n) \) Find first occurrence
bisect_right(a, x) Rightmost insertion index \( O(\log n) \) Find end of duplicates
insort(a, x) None (modifies list) \( O(n) \) Insert keeping order
insort_left(a, x) None (modifies list) \( O(n) \) Insert before duplicates

Question 1 of 5

What is the worst-case time complexity of binary search on a sorted list of \( n \) elements?

Question 2 of 5

Given arr = [1, 4, 4, 4, 8, 10], what does bisect.bisect_left(arr, 4) return?

Question 3 of 5

In a manual binary search, you set lo = mid instead of lo = mid + 1. What is the most likely result?

Question 4 of 5

You have a sorted list of 1,000,000 elements. What is the maximum number of comparisons binary search will make?

Question 5 of 5

Given arr = [2, 5, 5, 5, 8], how would you compute the number of 5s using bisect?