Stop looking at everything.
Exploit sorted order to shrink a search interval after every comparison.
01 Model the idea
Binary search maintains an interval that could contain a target. Comparing with its midpoint lets you discard approximately half of that interval. This gives logarithmic comparisons for sorted random-access data. The precondition matters: searching unsorted values with this algorithm can miss an item that is present.
If present, the target remains inside the current candidate interval.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
SET low and high to the candidate interval
WHILE the interval is nonempty
compare the midpoint with the target
keep only the possible half
RETURN not foundFind 31 in sorted input. The orange interval is the remaining candidate range.
Change the experiment +
Values are sorted for this search. Preparation sorting is not included in the comparison count.
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def binary_search(values, target):
low, high = 0, len(values) - 1
while low <= high:
middle = (low + high) // 2
if values[middle] == target: return middle
if values[middle] < target: low = middle + 1
else: high = middle - 1
return -1
print(binary_search([3, 8, 12, 20, 31], 20))
print(binary_search([3, 8, 12, 20, 31], 7))3 -1
- 1
low and high describe an inclusive interval. Each update removes the midpoint because it has already been checked.
- 2
When low exceeds high, no candidate remains. Returning -1 is the example’s explicit not-found contract, not a Python indexing recommendation.
- 3
The bisect module finds insertion boundaries. bisect_left returns a possible position, so check the position is in range and equals the target before treating it as a successful search.
04 Count the cost
O(log n) comparisons on sorted random-access data
O(1) auxiliary
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use bisect_left to find 12 and report whether it is present.
Reveal one possible solution +
from bisect import bisect_left
values = [3, 8, 12, 20]
index = bisect_left(values, 12)
print(index < len(values) and values[index] == 12)06 Check your reasoning
What is a necessary precondition for this search?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.