Binary Search Questions I Overcomplicated

Four binary search problems I made harder than they needed to be. Each shows the version I wrote in the loop and the version that should have been my first instinct, with invariants written down.

Question Bundle
JavaScript
4 questions
algorithms
binary-search
invariants
andresokonkwo

By @andresokonkwo

November 28, 2025

·

Updated August 9, 2026

378 views

8

Rate

Find the leftmost index of a target in a sorted array, or -1 if absent. I wrote three off-by-ones in a row in the loop before getting it right.

The version that finally worked

The invariant I write at the top before any code: arr[lo..hi) is the half-open candidate window, every index left of lo is strictly less than target, every index at or right of hi is strictly greater-or-equal to target.

function leftmost(arr, target) {
    let lo = 0;
    let hi = arr.length - 1;
    while (lo <= hi) {
        const mid = (lo + hi) >> 1;
        if (arr[mid] >= target) {
            hi = mid - 1;
        } else {
            lo = mid + 1;
        }
    }
    // Fragile: with the inclusive convention, lo can land past the right edge.
    return arr[lo] === target ? lo : -1;
}