JavaScript Snippet

Lower-Bound and Upper-Bound Binary Search

Difficulty: Medium

Lower-bound and upper-bound binary search are the two primitives every other range query depends on. Lower-bound returns the first index where a value could be inserted; upper-bound returns the first index strictly greater than the value. This snippet covers both forms, then composes them to count occurrences in a sorted array in O(log n).

Code Snippets
/

Lower-Bound and Upper-Bound Binary Search

Lower-Bound and Upper-Bound Binary Search

Lower-bound and upper-bound binary search are the two primitives every other range query depends on. Lower-bound returns the first index where a value could be inserted; upper-bound returns the first index strictly greater than the value. This snippet covers both forms, then composes them to count occurrences in a sorted array in O(log n).

JavaScript
Medium
3 snippets
algorithms
binary-search
code-template
two-pointers

1,179 views

34

Lower-bound returns the smallest index i such that arr[i] >= target. The half-open interval [lo, hi) and the arr[mid] < target test are the two pieces that distinguish it from a standard binary search: when the midpoint is too small, the target must live strictly to the right; otherwise the midpoint itself remains a candidate. The loop terminates with lo === hi, and that index is the answer. Time complexity is O(log n). This is the C++ std::lower_bound and Python bisect.bisect_left rewritten in JavaScript.