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.
Code
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)); // 5Output
Captured from a sandboxed run of this snippet in the build pipeline.
1
5How 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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.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.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.