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.
Code
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
4What 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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Binary Text ConverterConvert UTF-8 text to 8-bit binary groups and decode binary back to text with strict validation.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.