Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · DSA

Binary Search and Its Variants

Binary search in ten lines, then the variants interviews actually test: lower/upper bound, binary search on the answer, and rotated arrays, with Python code.

You have a sorted list of a million numbers and you need to know whether 7,342,118 is in it. A linear scan checks up to a million elements. Binary search checks at most 20, because each comparison throws away half of what is left, and log2(1,000,000) is just under 20. That is the whole idea, and it is also why interviewers like it: the algorithm itself takes ten lines, so the question is really about whether you can spot that a problem is binary-searchable and whether you can write the boundaries without an off-by-one error.

The mechanics

Binary search needs two things: a range that is sorted (or more generally, monotonic, which we will come back to) and random access, so that looking at the middle element is O(1). Arrays qualify; linked lists do not.

Keep two pointers, lo and hi, that bound the region where the answer could still be. Look at the middle, compare, and move one pointer so the region halves. Stop when the region is empty.

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Two small things in that code matter in interviews. lo + (hi - lo) // 2 instead of (lo + hi) // 2 avoids integer overflow in Java and C++, where lo + hi can exceed 2^31 - 1; in Python it does not matter but interviewers notice if you know why. And the loop condition is lo <= hi with mid ± 1 updates, so the region shrinks on every iteration and the loop always ends.

Time is O(log n), space is O(1) for the iterative version. A recursive version uses O(log n) stack space for no benefit, so write it iteratively.

Worked example

Search for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91].

  • lo=0, hi=9, mid=4, arr[4]=16 < 23, so lo=5.
  • lo=5, hi=9, mid=7, arr[7]=56 > 23, so hi=6.
  • lo=5, hi=6, mid=5, arr[5]=23. Found at index 5.

Three comparisons for ten elements. Now search for 24 on the same array: the third step gives arr[5]=23 < 24, so lo=6; then mid=6, arr[6]=38 > 24, so hi=5; now lo > hi and we return -1. Notice where the pointers ended up: lo is 6, which is exactly where 24 would be inserted to keep the array sorted. The variants below all build on that property.

The variant that matters most: first and last occurrence

The plain version returns some index of the target. With duplicates, [1, 2, 2, 2, 3], it might return index 1, 2 or 3 depending on where mid lands. Most real questions want the first or the last one, or the insertion point. The trick is to stop returning early and let the loop run to the end.

def lower_bound(arr, target):
    # first index i such that arr[i] >= target
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

Here hi starts at len(arr), the range is half-open [lo, hi), and the loop runs while lo < hi. When it ends, lo == hi and that index is the first element not less than the target, or len(arr) if every element is smaller. upper_bound is the same with <= in the comparison: it returns the first index with arr[i] > target.

With those two functions you get, in one line each: first occurrence is lower_bound, last occurrence is upper_bound - 1, count of a value is upper_bound - lower_bound, and "does it exist" is lower_bound < len(arr) and arr[lower_bound] == target. Python ships both as bisect.bisect_left and bisect.bisect_right, and C++ has std::lower_bound and std::upper_bound.

Pick one template, either closed [lo, hi] with lo <= hi, or half-open [lo, hi) with lo < hi, and use it every time. Mixing them is where the off-by-one bugs come from.

Binary search on the answer

The array does not have to be a literal array, and this is the variant most medium and hard problems use. All you need is a function f(x) over a range of candidate answers that is false up to some point and true after it (or the reverse). Then you binary search for the boundary.

Classic example, Koko Eating Bananas (LeetCode 875): given piles of bananas and h hours, find the minimum eating speed k such that Koko finishes in time. For any speed k, you can check in O(n) whether she finishes: sum of ceil(pile / k) over the piles, compared with h. If speed k works, every faster speed also works. So the predicate "finishes in time at speed k" is false, false, false, true, true, true across k = 1, 2, 3, ..., and you binary search on k.

import math

def min_eating_speed(piles, h):
    lo, hi = 1, max(piles)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        hours = sum(math.ceil(p / mid) for p in piles)
        if hours <= h:
            hi = mid        # mid works, try slower
        else:
            lo = mid + 1    # too slow
    return lo

That is lower_bound again, with arr[mid] < target replaced by "mid is too slow". Same shape appears in Split Array Largest Sum (410), Capacity to Ship Packages (1011), Minimum Days to Make Bouquets (1482), and Allocate Minimum Pages, which is the GeeksforGeeks favourite. If a problem says "minimise the maximum" or "maximise the minimum" and you can write a cheap yes/no check for a candidate, it is almost always this.

Rotated sorted array

Search in Rotated Sorted Array (LeetCode 33) is the other variant that comes up constantly. The array [4, 5, 6, 7, 0, 1, 2] is sorted but rotated, so a plain binary search breaks. The fix: at each step, one of the two halves [lo, mid] or [mid, hi] is guaranteed to be sorted. Check which one by comparing arr[lo] with arr[mid]. If the target lies inside the sorted half's range, go there; otherwise go to the other half. Still O(log n). Find Minimum in Rotated Sorted Array (153) uses the same observation to locate the pivot.

Questions interviewers ask on this

  • Implement binary search, then: what if there are duplicates? What if I want the first one? (They are testing whether you know lower_bound.)
  • Why lo + (hi - lo) // 2? (Overflow.)
  • Search Insert Position (35), First Bad Version (278), Find Peak Element (162), Sqrt(x) (69). All plain binary search or binary search on the answer.
  • Koko Eating Bananas (875), Capacity to Ship Packages (1011), Allocate Minimum Pages. Binary search on the answer with an O(n) check.
  • Search in Rotated Sorted Array (33) and Find Minimum in Rotated Sorted Array (153).
  • Median of Two Sorted Arrays (4), the hard one; the O(log(min(m, n))) solution binary searches the partition point in the shorter array.
  • Find First and Last Position of Element (34), which is lower_bound plus upper_bound.

For each, the follow-up to expect is "what is the time complexity of the check function?" since the total is O(check × log(range)).

Go deeper

  • LeetCode's Binary Search study plan covers the problems above in order of difficulty.
  • The bisect module docs in Python, especially the recipes section, show how bisect_left and bisect_right replace hand-written loops.
  • "Binary Search" on cp-algorithms.com has the cleanest write-up of the half-open template and binary search on the answer.
  • Jon Bentley's Programming Pearls reports that in his classes only about 10% of professional programmers wrote a correct binary search on the first try; the chapter on it is worth the hour.