Binary Search · Pattern 1 of 8

Exact search and binary search inside a design

Find an exact value in a sorted array, then use the same loop inside data structures that are sorted by time or by running sum.

2 variations · 4 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A sorted array and one exact value to find
  • Events stored in time order, queried as "the latest value at or before time t"
  • Picking an index by weight, using a running (prefix) sum

The template

Basics
int search(int[] a, int target) {
    int lo = 0, hi = a.length - 1;          // the answer is in [lo, hi]
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;  // target is right of mid
        else hi = mid - 1;                  // target is left of mid
    }
    return -1;                              // not found
}

The variations

  1. 1Exact match

    Closed range [lo, hi], loop while lo <= hi, return on a hit and step past mid otherwise. This is the classic version every other pattern builds on.

  2. 2Binary search inside a design

    Data that only ever grows in time order is already sorted. Store it in a list per key, then binary search the query: the last entry with time ≤ t, or the first running sum ≥ a random number.

Mistakes to avoid

  • Using lo < hi with this template and never checking the last element.
  • Forgetting that a design problem often wants "at or before t", which is an upper bound minus one, not an exact match.
Next: Lower bound, upper bound, floor and ceiling →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.