Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Search

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.

2 practice exercises17 interview problems

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.

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.
Print Output
print(find_first_true([False, True, True, True, True])) 1
print(find_first_true([False, False])) 2

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.

The Python bisect reference(opens in a new tab) provides library boundary semantics. Cutting Ribbons(opens in a new tab) transfers the same proof to a numeric answer space.

Templates To Memorize

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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Iterative binary searchO(log n)O(log n)O(1) indexing/comparison; expensive predicates multiply this bound.

Space

O(1) search state; O(log n) visited indexes in the decision-trace Lab.

Assumptions

  • Repeated slicing copies elements and can turn the total work into O(n).
  • The no-true boundary n is a valid insertion point, not a usable element index.

Invariants Worth Saying Aloud

  1. Exact-search candidates lie in the closed interval [left, right].
  2. For the half-open boundary template, positions before left are false and positions at or beyond right are true or the n sentinel.

When To Use Or Avoid Binary Search

Use It When

  • Use bisection for repeated ordered queries or a numeric answer space with a proved monotone predicate.
  • Retain a true midpoint when looking for the first true position.

Choose Another Tool When

  • An arbitrary unsorted sequence does not support the same discard proof.
  • Sorting for a single lookup costs O(n log n) and may lose original positions.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Dropping a true midpoint from a boundary interval

If mid 1 is already the first true position, right = mid - 1 excludes a legal answer under a half-open template.

Prevent it: For first-true [left,right), set right = mid.

Avoid

right = mid - 1

Use instead

right = mid

Failing to advance after a false midpoint

With a one-element false interval, left = mid leaves the interval unchanged and repeats forever.

Prevent it: Discard the inspected false position too: left = mid + 1.

Avoid

left = mid

Use instead

left = mid + 1

Converting the no-true insertion point to -1

For all-false flags the insertion boundary is len(flags). Returning -1 violates that boundary contract.

Prevent it: Return the converged boundary even when it equals n.

Avoid

answer = left if left < len(flags) else -1

Use instead

answer = left

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.