JavaScript Snippet

Binary Search Template

Difficulty: Easy

Binary search is the most asked algorithm in interviews and the easiest to get wrong: off-by-one bugs, infinite loops, integer overflow on the midpoint. This snippet covers the iterative bounds template that always terminates, a recursive variant for contrast, and a found-or-insertion-point version that returns where the value would go if absent. The same skeleton powers the lower-bound and upper-bound variants in the next entry.

Code Snippets
/

Binary Search Template

Binary Search Template

Binary search is the most asked algorithm in interviews and the easiest to get wrong: off-by-one bugs, infinite loops, integer overflow on the midpoint. This snippet covers the iterative bounds template that always terminates, a recursive variant for contrast, and a found-or-insertion-point version that returns where the value would go if absent. The same skeleton powers the lower-bound and upper-bound variants in the next entry.

JavaScript
Easy
3 snippets
algorithms
binary-search
code-template
two-pointers

967 views

17

The closed-interval template uses lo <= hi and updates with mid + 1 and mid - 1. The two updates are what guarantee termination: every iteration removes at least one index from consideration. Using (lo + hi) >>> 1 is the safe midpoint formula in JavaScript: the unsigned right shift avoids overflow that the equivalent (lo + hi) / 2 would suffer in languages with fixed-width integers. Time complexity is O(log n) and space is O(1). Memorise this exact shape; almost every binary search variant is one of these three lines changed.