Binary search boundaries
Binary search boundaries are found with a half-open range [lo, hi): if (a[mid] < x) lo = mid + 1; else hi = mid; stops at lower_bound, the first position ≥ x, and upper_bound − lower_bound counts how often x appears.
Last lesson's binary search, with repeated values, finds "one of them". But real questions are often: where is the first person scoring at least 60? How many scored exactly 85? To insert a value and keep the array sorted, where does it go? These are all boundary questions, and nearly every binary search written wrong in an interview is wrong at a boundary.
The first ≥ x: lower_bound
Put it another way: the array splits into two runs, the left all < x and the right all ≥ x, and we want the line between them. Find it with a half-open range [lo, hi):
- Start with
lo = 0, hi = n(the line could be at the very end, at n: everything smaller than x). a[mid] < x: mid is in the left run, the line is right of mid,lo = mid + 1.- Otherwise mid is in the right run, and the line is at mid or left of it,
hi = mid(not mid − 1: mid itself might be the answer). - Stop when
lo == hi: lo is the line.
lo↑hi↑mid1int lo = 0, hi = n;2while (lo < hi) {3 int mid = lo + (hi - lo) / 2;4 if (a[mid] < x) lo = mid + 1;5 else hi = mid;6}7return lo;
Use lower_bound to look for 7 in 2 4 4 4 7 9 (n = 6). Which mids does it look at, and what does it return?
The first > x, and what you can build from it
Change one symbol in the first level's lower_bound and it finds the first > x.
Change the condition a[mid] < x to a[mid] <= x and you find the first > x (upper_bound). With these two, everything else can be put together:
| To find | How |
|---|---|
| The first ≥ x | lower_bound(x) |
| The first > x | upper_bound(x) |
| How many times x appears | upper_bound(x) − lower_bound(x) |
| The last ≤ x | upper_bound(x) − 1 |
| Where x goes to keep it sorted | lower_bound(x) |
C++'s std::lower_bound and Python's bisect_left are this function.
1#include <stdio.h>2 3int lower(int a[], int n, int x) { // the first >= x4 int lo = 0, hi = n;5 while (lo < hi) {6 int mid = lo + (hi - lo) / 2;7 if (a[mid] < x) lo = mid + 1;8 else hi = mid;9 }10 return lo;11}12 13int upper(int a[], int n, int x) { // the first > x14 int lo = 0, hi = n;15 while (lo < hi) {16 int mid = lo + (hi - lo) / 2;17 if (a[mid] <= x) lo = mid + 1;18 else hi = mid;19 }20 return lo;21}22 23int main(void) {24 int a[] = {58, 60, 60, 72, 85, 85, 85, 91};25 int n = 8;26 printf("the first >= 60 is at index %d\n", lower(a, n, 60));27 printf("85 appears %d times\n", upper(a, n, 85) - lower(a, n, 85));28 printf("the last <= 80 is %d\n", a[upper(a, n, 80) - 1]);29 printf("70 goes at index %d\n", lower(a, n, 70));30 return 0;31}
the first >= 60 is at index 1 85 appears 3 times the last <= 80 is 72 70 goes at index 3
a = 1 3 3 3 5 8, x = 3. What are lower_bound(x) and upper_bound(x)?
To turn lower_bound into upper_bound (the first > x), what goes in the condition? The program prints how many times 85 appears and the index of the first > 60: it should be 3 3.
1#include <stdio.h>2 3int lower(int a[], int n, int x) {4 int lo = 0, hi = n;5 while (lo < hi) {6 int mid = lo + (hi - lo) / 2;7 if (a[mid] < x) lo = mid + 1;8 else hi = mid;9 }10 return lo;11}12 13int upper(int a[], int n, int x) {14 int lo = 0, hi = n;15 while (lo < hi) {16 int mid = lo + (hi - lo) / 2;17 if (a[mid] x) lo = mid + 1;18 else hi = mid;19 }20 return lo;21}22 23int main(void) {24 int a[] = {58, 60, 60, 72, 85, 85, 85, 91};25 printf("%d %d\n", upper(a, 8, 85) - lower(a, 8, 85), upper(a, 8, 60));26 return 0;27}
a[mid] <= x, mid is still in the left part, so lo = mid + 1. With < it's back to lower_bound, and the count of 85s comes out 0.The first and last appearance
✓Put together x's first and last indexes from lower and upper; if x isn't in the array, print -1 -1.
3 5 -1 -1
1#include <stdio.h>2 3int lower(int a[], int n, int x) {4 int lo = 0, hi = n;5 while (lo < hi) {6 int mid = lo + (hi - lo) / 2;7 if (a[mid] < x) lo = mid + 1;8 else hi = mid;9 }10 return lo;11}12 13int upper(int a[], int n, int x) {14 int lo = 0, hi = n;15 while (lo < hi) {16 int mid = lo + (hi - lo) / 2;17 if (a[mid] <= x) lo = mid + 1;18 else hi = mid;19 }20 return lo;21}22 23void range(int a[], int n, int x) {24 // l = lower; l == n or a[l] != x: none; otherwise the last is upper - 125 printf("-1 -1\n");26}27 28int main(void) {29 int a[] = {5, 7, 7, 8, 8, 8, 10};30 range(a, 7, 8);31 range(a, 7, 6);32 return 0;33}
The wrong way: a version that loops for ever
For "the last ≤ x", some write it like this: the left run is ≤ x, and when a[mid] <= x, mid may be the answer, so lo = mid.
1#include <stdio.h>2 3int main(void) {4 int a[] = {1, 3, 5, 5, 5, 8, 9};5 int x = 8, lo = 0, hi = 6, rounds = 0;6 while (lo < hi) {7 int mid = (lo + hi) / 2;8 if (a[mid] <= x) lo = mid; // the mistake9 else hi = mid - 1;10 if (++rounds == 20) {11 printf("still going at round 20: lo = %d, hi = %d, mid always %d\n", lo, hi, (lo + hi) / 2);12 return 0;13 }14 }15 printf("index %d\n", lo);16 return 0;17}
still going at round 20: lo = 5, hi = 6, mid always 5
Looking for 8, it goes wrong when two are left: lo = 5, hi = 6, mid = (5 + 6) / 2 = 5, equal to lo again. a[5] <= 8 holds, lo = mid is still 5, the range doesn't shrink at all, and it never gets out.
There's one rule: the range must get smaller every round. With lo = mid, round mid up: mid = (lo + hi + 1) / 2, so mid is always bigger than lo; with hi = mid (as in lower_bound), round it down. If you can't remember, always put it together from lower_bound and upper_bound, as in the first level.
lower_bound in 2 4 4 4 7 9 for 4, 5 and 10: what does it print?
1#include <stdio.h>2 3int lower(int a[], int n, int x) {4 int lo = 0, hi = n;5 while (lo < hi) {6 int mid = lo + (hi - lo) / 2;7 if (a[mid] < x) lo = mid + 1;8 else hi = mid;9 }10 return lo;11}12 13int main(void) {14 int a[] = {2, 4, 4, 4, 7, 9};15 printf("%d %d %d\n", lower(a, 6, 4), lower(a, 6, 5), lower(a, 6, 10));16 return 0;17}
lower_bound uses hi = mid. How must mid be worked out then?
hi = mid really shrinks the range, and so does lo = mid + 1. Round up, and with two left mid equals hi: hi = mid changes nothing and it's stuck.This "last ≤ x" uses lo = mid, and looking for 8 it gets stuck; rounds catches it and it prints -1. Change only the number in the green box so mid rounds up, and it prints 5 4.
1#include <stdio.h>2 3int last_le(int a[], int n, int x) {4 int lo = 0, hi = n - 1, rounds = 0;5 while (lo < hi) {6 int mid = (lo + hi + ) / 2;7 if (a[mid] <= x) lo = mid;8 else hi = mid - 1;9 if (++rounds > 100) return -1;10 }11 return lo;12}13 14int main(void) {15 int a[] = {1, 3, 5, 5, 5, 8, 9};16 printf("%d %d\n", last_le(a, 7, 8), last_le(a, 7, 5));17 return 0;18}
5 4
(lo + hi + 1) / 2 rounds up, so mid is always bigger than lo and lo = mid shrinks the range every time. With lo = 5, hi = 6 left, mid becomes 6, a[6] = 9 > 8, hi = 5, and it gets out.Searching for the answer
Binary search isn't only for arrays. Whenever a problem becomes "the bigger the answer, the easier it is to satisfy" (or the harder), you can binary search the answer itself. Take ⌊√n⌋: "k × k ≤ n" holds for small k and fails for big k, and we want the last k for which it holds.
1#include <stdio.h>2 3int main(void) {4 long long n = 2000000000; // 2 billion5 long long lo = 0, hi = n + 1; // find the first k with k * k > n6 while (lo < hi) {7 long long mid = lo + (hi - lo) / 2;8 if (mid * mid <= n) lo = mid + 1;9 else hi = mid;10 }11 printf("sqrt(%lld) rounded down is %lld\n", n, lo - 1);12 return 0;13}
sqrt(2000000000) rounded down is 44721
2 billion takes just 31 rounds. Note the long long: with mid near 2 billion, mid × mid overflows an int. Interview questions like "the smallest capacity", "the fewest days" or "the smallest possible maximum" are mostly searching for the answer: first write a function "given this answer, does it work?", then binary search.
In exams: if a binary search question has repeated values, settle first which one you want. When writing it, decide first whether the range is [lo, hi] or [lo, hi), then how each branch shrinks it, and last check whether one or two elements left could get it stuck.
What kind of problem allows binary search on the answer?
4 piles of bananas, 3, 6, 7 and 11, eating from one pile per hour, at k = 3 bananas an hour (a pile with fewer than 3 left still takes an hour). How many hours in all?
The slowest speed
✓4 piles of bananas, 3, 6, 7 and 11, to be eaten within 8 hours; each hour you eat from one pile only, k bananas an hour (a pile with fewer than k still takes the hour). What's the smallest k? ok(k) is written; finish the binary search for the first k where ok holds.
4
1#include <stdio.h>2 3int piles[] = {3, 6, 7, 11};4int n = 4, h = 8;5 6int ok(int k) { // can speed k finish within h hours?7 int hours = 0;8 for (int i = 0; i < n; i++)9 hours += (piles[i] + k - 1) / k; // rounded up10 return hours <= h;11}12 13int main(void) {14 int lo = 1, hi = 11; // the answer is between 1 and 1115 // the first k that is ok: ok(mid) holds, hi = mid; otherwise lo = mid + 116 printf("%d\n", lo);17 return 0;18}
Summary
Binary search boundaries: find the line
- Half-open [lo, hi): lo = 0, hi = n, carry on while lo < hi
- a[mid] < x gives lo = mid + 1, otherwise hi = mid: the first ≥ x
- How many = upper − lower; the last ≤ x = upper − 1
- The range must shrink every round: with lo = mid, round mid up
- Search for the answer: when "does it work?" changes one way, find the first that works
1int lo = 0, hi = n;2while (lo < hi) {3 int mid = lo + (hi - lo) / 2;4 if (a[mid] < x) lo = mid + 1; else hi = mid;5}