Binary Search Variant With Lower Bound (JavaScript)

Find the leftmost position where a sorted array can accept a target using binary search with a lower-bound variant that returns insertion index for duplicates.

JavascriptData Fetching

Code

javascriptsnippet
13 lines
function lowerBound(arr, target) {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

const arr = [1, 2, 2, 3, 4, 6];
console.log(lowerBound(arr, 2)); // 1
console.log(lowerBound(arr, 5)); // 5

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1
5

How it works

Binary Search Variant With Lower Bound (JavaScript) keeps everything in the functions mid and lowerBound.

Repetition is confined to while (lo < hi) — the rest of the file is straight-line.

Applying it

Signature: const mid = (lo + hi)

Statements that matter

if (arr[mid] < target) lo = mid + 1;
const arr = [1, 2, 2, 3, 4, 6];
let lo = 0, hi = arr.length;

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `mid`, `lowerBound` at load time.