Lower and Upper Bound Binary Search

Find the first and last insertion points for a value in a sorted array with a custom comparator, then count duplicates in logarithmic time.

JavascriptData Integrity

Code

javascriptsnippet
41 lines
export function lowerBound(array, target, compare = defaultCompare) {
  assertArray(array);
  let low = 0;
  let high = array.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    if (compare(array[mid], target) < 0) low = mid + 1;
    else high = mid;
  }
  return low;
}

export function upperBound(array, target, compare = defaultCompare) {
  assertArray(array);
  let low = 0;
  let high = array.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    if (compare(array[mid], target) <= 0) low = mid + 1;
    else high = mid;
  }
  return high;
}

export function countOccurrences(array, target, compare) {
  return upperBound(array, target, compare) - lowerBound(array, target, compare);
}

function defaultCompare(left, right) {
  return left < right ? -1 : left > right ? 1 : 0;
}

function assertArray(array) {
  if (!Array.isArray(array)) throw new TypeError("array must be an array");
}

const scores = [10, 20, 20, 20, 35, 50];
console.log(lowerBound(scores, 20));
console.log(upperBound(scores, 20));
console.log(countOccurrences(scores, 20));
console.log(lowerBound(scores, 25));

Output

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

1
4
3
4

What the code does

Count the functions mid, lowerBound, upperBound and countOccurrences as the entire surface area of Lower and Upper Bound Binary Search.

The failure path is explicit — TypeError is raised when the guard condition holds.

Using it

The primary signature is export function lowerBound(array, target, compare = defaultCompare)

lowerBound is the public entry point; everything else in the file exists to support it.

Key statements

return upperBound(array, target, compare) - lowerBound(array, target, compare);
if (!Array.isArray(array)) throw new TypeError("array must be an array");
return left < right ? -1 : left > right ? 1 : 0;

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code throws `TypeError`. Handle it at the call site or let it propagate deliberately.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `mid`, `lowerBound`, `upperBound` at load time.