Halve a sorted equality-search interval or a false-to-true predicate boundary. Keep inclusive exact-search updates separate from half-open insertion-boundary updates, and prove each discarded region cannot contain the answer.
Recognize it when Random-access values are sorted under the same comparison used by the search.
Checking your account…
Binary Search Code Labs
Search a Monotone Boundary
Binary search is not merely “search a sorted array.” It searches a monotone decision space: once a predicate becomes true, it stays true, or comparisons consistently discard one side. Prove that shape before writing the loop.
Write the Loop Invariant
For this half-open template, [left, right) contains unknown element indexes, while the possible first-true boundary lies in the inclusive range [left, right]. Every index before left is known false; right is a retained known-true anchor when below n, or the sentinel n. Each iteration shrinks the unknown interval while retaining all possible boundary positions. At left == right, no unknown element remains and that shared position is the answer.
Trace Exact-Search Decisions
Reference
def binary_search_decisions(values, target):
left, right = 0, len(values) - 1
decisions = []
while left <= right:
mid = (left + right) // 2
decisions.append(mid)
if values[mid] == target:
break
if values[mid] < target:
left = mid + 1
else:
right = mid - 1
return decisions
Practice
Implement binary_search_decisions(values, target). values is sorted. Return the indexes inspected by a standard inclusive binary search, stopping when target is found or the interval is empty.
Public tests
Trace inspected midpoints
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace Exact-Search Decisions
def binary_search_decisions(values, target):
left, right = 0, len(values) - 1
decisions = []
while left <= right:
mid = (left + right) // 2
decisions.append(mid)
if values[mid] == target:
break
if values[mid] < target:
left = mid + 1
else:
right = mid - 1
return decisions
Choose Exact Search or First True
Exact search can stop on equality and often uses an inclusive right edge. Boundary search continues after finding a true candidate, retaining it while searching left. Pick one template deliberately; mixing their update rules creates skipped candidates or infinite loops.
Find the First True Boundary
This complete example is available in the associated exercise with paid access.
Binary search for the first True: if mid is True, save it and keep looking to the left.
Keep the True Candidate While Moving Left
Run the existing boundary Lab, not the adjacent exact-search template. Predict the interval after each midpoint for five flags, then compare the all-false insertion result.
Step
Executed statement
State
Why
Initial interval
left, right = 0, len(flags)
left=0, right=5
The sentinel 5 represents no true element.
Inspect 2
if flags[mid]: right = mid
mid=2 is True; right=2
Retain 2 as a possible boundary and discard only later positions.
Inspect 1
right = mid
left=0, right=1
True at 1 moves the possible boundary left again.
Inspect 0
left = mid + 1
left=1, right=1
False at 0 excludes that index; convergence fixes the boundary.
All-false call
return left
2 == len(flags)
The valid insertion point is after all existing elements.
The other Lab records inclusive exact-search decisions and can stop at equality. When presenting a solution, state one interval convention and derive its updates rather than memorizing interchangeable-looking lines.
Choose Binary Search or a Hash Lookup
Use binary search when order or a monotone answer space already exists and O(log n) queries are sufficient. Use a hash lookup for average O(1) membership when ordering is irrelevant and extra space is acceptable. Sorting solely for one lookup usually costs more than a scan.
Explain It in an Interview
Say: “The predicate is monotone. My unknown element interval is half-open, and the possible boundary includes its right anchor; false discards through mid, true retains mid as that anchor. The interval shrinks every iteration.” Then cover the empty input and no-true sentinel, and derive O(log n) time from repeated halving and O(1) space.
Learn this shape by heart; most problems in this family change only one or two lines of it.
Binary search for a value
Closed range, loop while left <= right, always step past mid.
The data is sorted and you look for one exact value.
Trigger words
sorted + find target
o(log n)
search rotated array
halve the search space
median of two sorted arrays
def binary_search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Spot it when
Sorted array and 'find the index of target'.
The problem asks for O(log n).
Remember
[left, right] is the part that may still contain the target.
mid + 1 and mid - 1 always shrink the range, so the loop cannot get stuck.
How problems bend it
Rotated sorted array: One half around mid is always sorted; check whether the target lies in that half.
2D sorted matrix: Treat the matrix as one sorted list: row = mid // cols, col = mid % cols.
Binary search for the first match
Find the first True: if it works, save it and go left.
The positions split into a 'no' part followed by a 'yes' part and you need the first 'yes'.
Trigger words
first position
last position
insert position
smallest index such that
minimum of rotated array
peak of mountain
latest timestamp <= t
def first_true(nums, target):
left, right = 0, len(nums) - 1
answer = len(nums) # what to return if nothing matches
while left <= right:
mid = (left + right) // 2
if nums[mid] >= target: # the knob: the yes/no condition
answer = mid # mid works; maybe an earlier one does too
right = mid - 1
else:
left = mid + 1
return answer
Spot it when
'First/last position', 'insert position', 'smallest index such that ...'.
Searching a minimum in a rotated array or the peak of a mountain array.
Remember
Keep the best answer in a variable, so you never have to reason about where left ends up.
Change only the condition and the default answer for each new problem.
How problems bend it
Last position instead of first: When the condition holds, record mid and move left = mid + 1.
First and last position of a target: Run the template twice: first index >= target, and first index > target, minus one.
Python Version Note
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Binary Search proof does not depend on a minor Python release.