01

The bug

Search Insert Position asks for the index of target in a sorted array, or the index where it would be inserted. This solution looks right and passes two of the three examples in the problem statement.

Python: has a bug
def search_insert(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

For nums = [1, 3, 5, 6] and target = 7 it returns 3. The correct answer is 4, because 7 goes after the last element.

02

Step 1: shrink the failing input

A failing input with four elements has many moving parts. Remove elements while the failure remains, until nothing more can go.

[5, 6] with target 7 still fails. [6] with target 7 still fails: it returns 0 and should return 1. One element is the smallest failing case, and it already says a lot. With one element, lo and hi both start at 0, so the loop body never runs. The bug is not inside the loop.

03

Step 2: print the state, not the answer

The final answer only says that something went wrong. The values at each step say where. Print every variable the loop changes, once per round.

nums = [1, 3, 5, 6], target = 7
lo  hi  mid  nums[mid]  action
0   3   1    3          3 < 7, lo = 2
2   3   2    5          5 < 7, lo = 3
3   3   -    -          lo == hi, stop, return 3

Every step is correct on its own. lo moves right each time, as it should. The loop stops at 3 because hi is 3 and lo can never pass it. So the question becomes: why can hi not be 4?

04

Step 3: check the invariant at the start

Binary search relies on one rule: the answer is always between lo and hi. If the rule is true at the start and every step keeps it true, the result is correct.

Here the rule is false before the loop begins. The answer can be len(nums), when the target is larger than everything. But hi starts at len(nums) - 1, so that answer is outside the range from the first line. No loop can find a value the range never included.

Python: fixed
def search_insert(nums, target):
    lo, hi = 0, len(nums)        # the answer can be len(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

nums[mid] is still safe. Inside the loop lo < hi, so mid is always less than hi and never reaches len(nums).

05

A second bug: the loop that never ends

This version looks for the last index whose value is at most target. On [1, 3] with target 3 it runs forever.

Python: infinite loop
lo, hi = 0, len(nums) - 1
while lo < hi:
    mid = (lo + hi) // 2
    if nums[mid] <= target:
        lo = mid
    else:
        hi = mid - 1

Print the state: lo = 0, hi = 1, mid = 0, nums[0] = 1 <= 3, so lo = mid = 0. Nothing changed, and the next round is identical. With two elements left, (lo + hi) // 2 rounds down to lo, and lo = mid then moves nothing.

The check to make on any loop: does the range get smaller on every path? Here one path does not. The fix is to round up, mid = (lo + hi + 1) // 2, so that lo = mid always moves lo forward.

06

Step 4: handle too slow separately from wrong

A time limit error is a different problem from a wrong answer, and needs a different check. Do not look for a logic bug. Count the work.

A typical case is a line that hides a loop. In Python, if x in items scans the whole list when items is a list. Inside a loop over 100,000 elements, that is up to 10¹⁰ comparisons, which is far too many. Changing items to a set makes each check O(1) without touching the logic.

  • Find the largest input size in the constraints.
  • Count how many times the innermost line runs for that size.
  • Around 10⁸ simple steps is the usual limit. Above that, the algorithm needs to change, not the code.
07

Step 5: keep the failing input as a test

Every bug you fix gives you a test for free. Keep it, so the same bug cannot return while you change something else. Then let a slow, obviously correct version check many random inputs for you.

Python: saved cases and a random check
assert search_insert([6], 7) == 1
assert search_insert([1, 3, 5, 6], 7) == 4
assert search_insert([], 5) == 0

import random

def slow(nums, target):
    for i, x in enumerate(nums):
        if x >= target:
            return i
    return len(nums)

for _ in range(1000):
    nums = sorted(random.sample(range(20), random.randint(0, 6)))
    target = random.randint(-1, 21)
    assert search_insert(nums, target) == slow(nums, target), (nums, target)

The random check finds the first bug in this article almost at once, because any target larger than the whole array triggers it.

08

The method in short

The same steps work for any algorithm, not only binary search.

  • Shrink the input until it cannot fail any smaller.
  • Print the state each round and find the first wrong value.
  • Say the invariant and check it at the start, not only inside the loop.
  • For loops that hang, check that every path makes the range smaller.
  • Treat slow and wrong as two separate problems.
  • Save each failing input as a test.