Searching & Binary Search

Linear search, binary search done right, lower/upper bounds, and binary search on the answer.

Beginner 3 min readLesson 5 of 18 Interview Q&A

Linear search checks elements one by one: O(n), works on anything. Binary search needs the data sorted (or, more generally, a monotonic condition) and halves the search space every step: O(log n). A billion sorted items need at most 30 comparisons.

InteractiveBinary search
2
0
lo
5
1
8
2
12
3
16
4
23
5
38
6
56
7
72
8
91
9
hi
Search for 23. lo=0, hi=9
1/7

The canonical implementation

int binarySearch(int[] a, int target) {
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {                       // search space [lo, hi] is non-empty
        int mid = lo + (hi - lo) / 2;        // avoids (lo + hi) overflow
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;   // discard left half including mid
        else hi = mid - 1;                   // discard right half including mid
    }
    return -1;                               // lo is the insertion point
}

Lower bound and upper bound

Most real uses aren't "is x present?" but "where is the first element ≥ x?" These use a half-open range [lo, hi) and never return early.

  • lower_bound(x): first index with a[i] >= x
  • upper_bound(x): first index with a[i] > x
  • Count of x = upper_bound(x) − lower_bound(x); first/last occurrence come for free.
int lowerBound(int[] a, int x) {
    int lo = 0, hi = a.length;               // [lo, hi)
    while (lo < hi) {
        int mid = (lo + hi) >>> 1;
        if (a[mid] < x) lo = mid + 1;        // use <= for upperBound
        else hi = mid;
    }
    return lo;                               // in [0, n]
}
// Library: Arrays.binarySearch returns -(insertionPoint) - 1 when absent;
// TreeSet.ceiling / floor for dynamic sets.

The general idea: search a monotonic predicate

Binary search works on any predicate P(i) that is false, false, …, false, true, true, … — find the first true. The array is just one example.

F0F1F2F3T4T5T6first true
Binary search finds the boundary of any monotonic predicate.

Binary search on the answer

When a problem asks for the minimum value that works and "works" is monotonic (if speed s works, any faster speed works too), binary search over the answer range and test feasibility.

Koko eating bananas: minimum eating speed to finish in h hours
int minEatingSpeed(int[] piles, int h) {
    int lo = 1, hi = Arrays.stream(piles).max().getAsInt();
    while (lo < hi) {
        int k = (lo + hi) >>> 1;
        long hours = 0;
        for (int p : piles) hours += (p + k - 1) / k;    // ceil(p / k)
        if (hours <= h) hi = k;                          // feasible: try slower
        else lo = k + 1;
    }
    return lo;
}

The same template solves: ship packages within D days, split array largest sum, minimum days to make bouquets, square root, and many "minimise the maximum" problems. More variants (rotated arrays, peaks, 2D matrices) in Modified binary search.

Other searches, briefly

  • Ternary search — maximum/minimum of a unimodal function: O(log n).
  • Exponential search — unbounded or very large sorted data: double hi until it passes the target, then binary search. O(log i).
  • Interpolation search — guesses position from values; O(log log n) on uniform data, O(n) worst.
  • Hash lookup — O(1) average membership, no ordering needed.
Key takeaways
  • Binary search needs sorted data or a monotonic predicate; it runs in O(log n).
  • Use lo + (hi − lo) / 2; be deliberate about closed [lo, hi] vs half-open [lo, hi).
  • lower_bound / upper_bound handle duplicates, insertion points and counts.
  • "Minimum x such that feasible(x)" ⇒ binary search on the answer.
Interview questions
QFind the first and last position of a target in a sorted array.medium

first = lowerBound(target); if it's out of range or a[first] != target, return [-1, -1]. last = upperBound(target) − 1. Two O(log n) searches.

QCompute the integer square root of x without library functions.easy

Binary search the largest m with m·m ≤ x over [0, x] (use long/64-bit for m·m). O(log x). Newton's method converges faster but binary search is easier to get right.

QHow do you avoid infinite loops in binary search?medium

Make sure the range strictly shrinks every iteration. With lo < hi and hi = mid, compute mid rounding down; if you use lo = mid, round up (mid = lo + (hi − lo + 1) / 2). Test on arrays of size 1 and 2.