Part 17 / Topic 8 of 20
Binary search (bisect)
Binary search finds a target in a sorted sequence by checking the middle item and throwing away the half that cannot contain the target - repeat until found or the range is empty. Each step halves the search space, so it takes O(log n) steps, dramatically fewer than scanning one by one (O(n)). Think of guessing a number between 1 and 100: "is it above 50?" cuts the possibilities in half every time, so you never need more than 7 guesses.
| Search | Requires sorted data? | Time |
|---|---|---|
linear scan (in, a for loop) |
no | O(n) |
binary search / bisect |
yes | O(log n) |
The standard library's bisect module does this for you:
import bisect
slots = sorted([9, 11, 13, 15, 17])
requested = 10
index = bisect.bisect_left(slots, requested) # first slot >= requested
print(slots[index] if index < len(slots) else None) # 11
leaderboard = [980, 1200, 1750]
bisect.insort(leaderboard, 1500) # insert while keeping it sorted
print(leaderboard) # [980, 1200, 1500, 1750]
Binary search also works on the answer itself, not just on data: "what is the smallest per-trip weight limit that still finishes all deliveries within 3 trips?" is monotonic (a bigger limit never needs more trips than a smaller one), which is exactly what binary search needs - narrow in on the smallest limit that still works, the same halving idea applied to a range of possible answers instead of a list of values.
Real-world example: bisect_left above is how a delivery app finds the next available time slot at or after a customer's requested time, out of a sorted list of open slots, in O(log n) instead of scanning the whole list.
⚠️ Binary search only works on sorted data; running it on an unsorted list gives a meaningless answer with no error. If the data isn't already sorted, sorting it first costs O(n log n) - still worth it if you will search it many times. And
bisect.insortfinds the spot in O(log n), but thelistinsert itself still shifts O(n) items — fine now and then, the wrong tool for millions of inserts.
Practice: search in sorted data (exact value, or first/last occurrence of it); find the correct insertion position to keep data sorted; "binary search on the answer" for a smallest/largest value that satisfies a yes/no condition.
Read more: the official bisect documentation.
Practice on LeetCode - start here: Binary Search · Search Insert Position · First Bad Version · Search a 2D Matrix · Search in Rotated Sorted Array · Koko Eating Bananas
Show the full practice list (16 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Guess Number Higher or Lower | Easy |
| Sqrt(x) | Easy |
| Valid Perfect Square | Easy |
| Arranging Coins | Easy |
| Peak Index in a Mountain Array | Medium |
| Find First and Last Position of Element in Sorted Array | Medium |
| Find Peak Element | Medium |
| Single Element in a Sorted Array | Medium |
| Find Minimum in Rotated Sorted Array | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Search in Rotated Sorted Array II | Medium |
| Time Based Key-Value Store | Medium |
| Capacity To Ship Packages Within D Days | Medium |
| Minimum Number of Days to Make m Bouquets | Medium |
| Find the Duplicate Number | Medium |
| Split Array Largest Sum | Hard |
| Median of Two Sorted Arrays | Hard |
Full program: examples/08_binary_search_bisect.py.
Exercise 8: Binary search — first bus at or after a time
Scenario: A bus stop's timetable is sorted. A commuter wants the first bus at or after the time they arrive.
What to do: Write first_bus_at_or_after(timetable: list[int], arrival: int) -> int | None using bisect.bisect_left. Print the result for three arrival times.
Starting data:
TIMETABLE = [540, 600, 660, 720, 780] # minutes after midnight
ARRIVALS = [550, 660, 800]
Sample output:
Arrive at 550 -> next bus at 600
Arrive at 660 -> next bus at 660
Arrive at 800 -> next bus at None
Show the solution to Exercise 8
"""Exercise 8: Binary search - first bus at or after a time.
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
import bisect
TIMETABLE = [540, 600, 660, 720, 780] # minutes after midnight
ARRIVALS = [550, 660, 800]
def first_bus_at_or_after(timetable: list[int], arrival: int) -> int | None:
index = bisect.bisect_left(timetable, arrival)
return timetable[index] if index < len(timetable) else None
def main() -> None:
for arrival in ARRIVALS:
bus = first_bus_at_or_after(TIMETABLE, arrival)
print(f"Arrive at {arrival} -> next bus at {bus}")
if __name__ == "__main__":
main()