Community Question Bundle

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.

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 May 18, 2026

377 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.