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.
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.
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.
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 \).
The Binary Search Algorithm
lo = 0 and hi = len(arr) - 1.mid = (lo + hi) // 2.arr[mid] == target, return mid.lo = mid + 1. Otherwise, set hi = mid - 1.Binary Search in Python
Flowchart: One Iteration
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.
bisect_left vs bisect_right
How to Apply Binary Search
bisect for insertion-point tasks.lo, inclusive hi for manual; bisect handles this internally.Example 1: Finding a Value
Search for 23 in [2, 5, 8, 12, 17, 23, 31, 44, 56].
Example 2: Using bisect for Lookup
Use bisect_left to check if a value exists, then use insort to add a new value.
Example 3: Counting Duplicates
How many times does 7 appear in [1, 3, 7, 7, 7, 9, 12]? Use both bisect functions:
Common Mistakes
lo < hi instead of lo <= hi can skip the last element. Be precise with your loop condition.lo = mid instead of lo = mid + 1 can cause an infinite loop when lo and hi are adjacent.len(arr). Always check i < len(arr) before accessing arr[i].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?
bisect_left returns the leftmost position where 4 could be inserted. The first 4 is at index 1, so the insertion point before it is 1.Question 3 of 5
In a manual binary search, you set lo = mid instead of lo = mid + 1. What is the most likely result?
lo and hi are adjacent (e.g., lo=3, hi=4), mid = (3+4)//2 = 3. Setting lo = mid keeps lo at 3 forever, causing an infinite loop.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?
bisect_left gives the index of the first 5, and bisect_right gives the index after the last 5. Subtracting: \( 4 - 1 = 3 \) occurrences.