JavaScriptMedium
Implement Binary Search
Binary search finds a target in a sorted array by repeatedly comparing it with the middle element and discarding the half that cannot contain it, giving O(log n) time; the classic pitfalls are off-by-one boundaries and forgetting the array must be sorted.
Iterative template
lo = 0,hi = arr.length - 1.- While
lo <= hi:mid = lo + ((hi - lo) >> 1). - If
arr[mid] === targetreturnmid; if smaller,lo = mid + 1; elsehi = mid - 1. - Return
-1when the range is empty.
Variants interviewers ask
- First/last occurrence of a duplicate value (keep searching left or right after a match).
- Lower bound / insertion point: the first index where
arr[i] >= target, used to insert while keeping order. - Search in a rotated sorted array.
- Binary search on the answer: the smallest capacity, speed or time that satisfies a condition (when the condition is monotonic).
- Custom comparator for objects (search by date or id).
Details worth mentioning
lo + ((hi - lo) >> 1)avoids overflow in languages with fixed-size integers; in JavaScriptMath.floor((lo + hi) / 2)is fine for normal array sizes.- Recursion works too but adds O(log n) stack space.
- Sorting first costs O(n log n), so binary search pays off when you search the same sorted data many times.
Code example
js
1function binarySearch(arr, target) {2 let lo = 0;3 let hi = arr.length - 1;4 while (lo <= hi) {5 const mid = lo + ((hi - lo) >> 1);6 if (arr[mid] === target) return mid;7 if (arr[mid] < target) lo = mid + 1;8 else hi = mid - 1;9 }10 return -1;11}1213// Lower bound: first index with arr[i] >= target (also the insertion point)14function lowerBound(arr, target, compare = (a, b) => a - b) {15 let lo = 0;16 let hi = arr.length; // note: exclusive upper bound17 while (lo < hi) {18 const mid = (lo + hi) >> 1;19 if (compare(arr[mid], target) < 0) lo = mid + 1;20 else hi = mid;21 }22 return lo;23}2425const sorted = [1, 3, 5, 7, 7, 7, 9, 11];26console.log(binarySearch(sorted, 9), binarySearch(sorted, 4)); // 6 -127console.log(lowerBound(sorted, 7), lowerBound(sorted, 8)); // 3 6 - first 7, and where 8 would go2829// Insert while keeping the array sorted30const scores = [10, 20, 30];31scores.splice(lowerBound(scores, 25), 0, 25);32console.log(scores); // [10, 20, 25, 30]3334// Search objects with a comparator35const events = [{ at: 100 }, { at: 200 }, { at: 300 }];36console.log(lowerBound(events, { at: 250 }, (a, b) => a.at - b.at)); // 23738// Binary search on the answer: smallest daily capacity to ship all packages in 5 days39function minCapacity(weights, days) {40 const canShip = (cap) => {41 let needed = 1, load = 0;42 for (const w of weights) {43 if (load + w > cap) { needed++; load = 0; }44 load += w;45 }46 return needed <= days;47 };48 let lo = Math.max(...weights), hi = weights.reduce((a, b) => a + b, 0);49 while (lo < hi) {50 const mid = (lo + hi) >> 1;51 canShip(mid) ? (hi = mid) : (lo = mid + 1);52 }53 return lo;54}55console.log(minCapacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)); // 15
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.