Binary Search · Pattern 2 of 8

Lower bound, upper bound, floor and ceiling

Find where a value would go: the first element ≥ x (lower bound) or > x (upper bound). Floor, ceiling, first and last position and counts all come from these two.

5 variations · 11 problems · 7 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

  • Where would x be inserted to keep the array sorted?
  • First or last position of a value, or how many times it appears
  • Closest, floor (largest ≤ x) or ceiling (smallest ≥ x)

The template

Bisect
// first index i with a[i] >= target; a.length if there is none
int lowerBound(int[] a, int target) {
    int lo = 0, hi = a.length;              // the answer is in [lo, hi]
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < target) lo = mid + 1;  // too small: answer is right of mid
        else hi = mid;                      // mid could be the answer
    }
    return lo;
}

// first index i with a[i] > target: the same loop with <=
int upperBound(int[] a, int target) {
    int lo = 0, hi = a.length;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (a[mid] <= target) lo = mid + 1;
        else hi = mid;
    }
    return lo;
}

The variations

  1. 1Lower bound: first element ≥ x

    The insert position, the ceiling and the first occurrence are all the lower bound. If lo == n there is no such element.

  2. 2Upper bound: first element > x, and floor

    The upper bound skips every copy of x. One step left of it is the floor: the largest element ≤ x, which also answers "the latest event at or before time t".

  3. 3Both bounds: first, last and count

    First position = lower bound. Last position = upper bound − 1. Count = upper bound − lower bound. Two O(log n) searches instead of a scan.

  4. 4Nearest value

    Find the lower bound, then compare the element there with the one just before it. The closer one is the answer; with a window, slide left or right from there.

    Now you solve
  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Starting with hi = n - 1: then "insert at the end" can never be returned.
  • Reading a[lo] without checking lo < n first.
  • Floor is upperBound(x) - 1, not lowerBound(x) - 1: the two differ when x is in the array.
Next: Binary search on a condition: first true →

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