Python Snippet

Python Binary Search Template

Difficulty: Easy

Binary search runs in O(log n) over any sorted array, but the off-by-one variations bite everyone. This entry ships three runnable templates: the equality search, the lower-bound (`bisect_left`) variant, and the upper-bound (`bisect_right`) variant. Each one handles every edge case the test list throws at it.

Code Snippets
/

Python Binary Search Template

Python Binary Search Template

Binary search runs in O(log n) over any sorted array, but the off-by-one variations bite everyone. This entry ships three runnable templates: the equality search, the lower-bound (`bisect_left`) variant, and the upper-bound (`bisect_right`) variant. Each one handles every edge case the test list throws at it.

Python
Easy
3 snippets
binary-search
algorithms
code-template
binary-search-templates

1,085 views

33

The template uses a closed interval [lo, hi]. lo <= hi is the loop condition because the interval is inclusive on both ends, and lo = mid + 1 / hi = mid - 1 shrink it without ever revisiting mid. Computing mid = (lo + hi) // 2 is safe in Python (ints are unbounded), so you do not need the lo + (hi - lo) // 2 trick that C and Java need. Test against empty arrays, single-element arrays, the first and last elements, and out-of-range values: every binary-search bug shows up there.