Binary search bounds and lower_bound
Binary search bounds handle repeats: lower_bound gives the first position not less than x, upper_bound the first greater than x, and their difference counts x; a half-open range avoids endless loops, and the same halving finds the smallest workable answer.
Last lesson's binary search, with repeated values, finds "one of them". Real questions are often: where is the first person scoring at least 60? How many scored exactly 85? To insert a number and keep things sorted, where does it go? These are all "boundary" problems, and when a binary search goes wrong in an interview, it's nearly always at a boundary.
The first ≥ x: lower_bound
Put another way: the array splits into two parts, a left part all < x and a right part all ≥ x, and what we want is the boundary between them. Look for it with the half-open range [lo, hi):
- Start with
lo = 0, hi = n(the boundary may be at the very end, at n: everything is less than x). a[mid] < x: mid is in the left part, the boundary is to the right of mid,lo = mid + 1.- Otherwise mid is in the right part, the boundary is at mid or left of it,
hi = mid(not mid − 1: mid itself may be the answer). - Stop when
lo == hi; lo is the boundary.
lo↑hi↑mid1int lo = 0, hi = (int)a.size();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 built:
| You want | 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 things sorted | lower_bound(x) |
1#include <iostream>2#include <vector>3using namespace std;4 5int lower(const vector<int>& a, int x) { // the first >= x6 int lo = 0, hi = (int)a.size();7 while (lo < hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] < x) lo = mid + 1;10 else hi = mid;11 }12 return lo;13}14 15int upper(const vector<int>& a, int x) { // the first > x16 int lo = 0, hi = (int)a.size();17 while (lo < hi) {18 int mid = lo + (hi - lo) / 2;19 if (a[mid] <= x) lo = mid + 1;20 else hi = mid;21 }22 return lo;23}24 25int main() {26 vector<int> a = {58, 60, 60, 72, 85, 85, 85, 91};27 cout << "index of the first >= 60: " << lower(a, 60) << endl;28 cout << "85 appears " << upper(a, 85) - lower(a, 85) << " times" << endl;29 cout << "the last <= 80 is " << a[upper(a, 80) - 1] << endl;30 cout << "70 goes at index " << lower(a, 70) << endl;31 return 0;32}
index of the first >= 60: 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 <iostream>2#include <vector>3using namespace std;4 5int lower(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size();7 while (lo < hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] < x) lo = mid + 1;10 else hi = mid;11 }12 return lo;13}14 15int upper(const vector<int>& a, int x) {16 int lo = 0, hi = (int)a.size();17 while (lo < hi) {18 int mid = lo + (hi - lo) / 2;19 if (a[mid] x) lo = mid + 1;20 else hi = mid;21 }22 return lo;23}24 25int main() {26 vector<int> a = {58, 60, 60, 72, 85, 85, 85, 91};27 cout << upper(a, 85) - lower(a, 85) << " " << upper(a, 60) << endl;28 return 0;29}
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.First and last occurrence
✓Use lower and upper to build the indexes where x first and last appears; if x isn't in the array, print -1 -1.
3 5 -1 -1
1#include <iostream>2#include <vector>3using namespace std;4 5int lower(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size();7 while (lo < hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] < x) lo = mid + 1;10 else hi = mid;11 }12 return lo;13}14 15int upper(const vector<int>& a, int x) {16 int lo = 0, hi = (int)a.size();17 while (lo < hi) {18 int mid = lo + (hi - lo) / 2;19 if (a[mid] <= x) lo = mid + 1;20 else hi = mid;21 }22 return lo;23}24 25void range(const vector<int>& a, int x) {26 // l = lower; l == a.size() or a[l] != x: none; otherwise the last is upper - 127 cout << "-1 -1" << endl;28}29 30int main() {31 vector<int> a = {5, 7, 7, 8, 8, 8, 10};32 range(a, 8);33 range(a, 6);34 return 0;35}
How not to: a version that loops forever
Looking for "the last ≤ x", some write this: the left part is the ≤ x one, and when a[mid] <= x mid may be the answer, so lo = mid. With the both-ends-included [lo, hi], looking for 8 in 1 3 5 5 5 8 9:
lo↑hi↑mid1while (lo < hi) {2 int mid = (lo + hi) / 2;3 if (a[mid] <= x) lo = mid; // the bug4 else hi = mid - 1;5}
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a = {1, 3, 5, 5, 5, 8, 9};7 int x = 8, lo = 0, hi = 6, rounds = 0;8 while (lo < hi) {9 int mid = (lo + hi) / 2;10 if (a[mid] <= x) lo = mid; // the bug11 else hi = mid - 1;12 if (++rounds == 20) {13 cout << "still going in round 20: lo = " << lo << ", hi = " << hi14 << ", mid is always " << (lo + hi) / 2 << endl;15 return 0;16 }17 }18 cout << "index " << lo << endl;19 return 0;20}
still going in round 20: lo = 5, hi = 6, mid is always 5
So that there is something to see, the program stops itself after 20 rounds; written like this for real, the program just hangs. There's one rule: the range must shrink every round. With lo = mid, round mid up: mid = (lo + hi + 1) / 2, so mid is always above lo; with hi = mid (as in lower_bound), round it down. If that's hard to remember, always build it from the lower_bound / upper_bound of the first two levels.
lower_bound in 2 4 4 4 7 9 for 4, 5 and 10: what does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int lower(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size();7 while (lo < hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] < x) lo = mid + 1;10 else hi = mid;11 }12 return lo;13}14 15int main() {16 vector<int> a = {2, 4, 4, 4, 7, 9};17 cout << lower(a, 4) << " " << lower(a, 5) << " " << lower(a, 10) << endl;18 return 0;19}
end().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 <iostream>2#include <vector>3using namespace std;4 5int last_le(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size() - 1, rounds = 0;7 while (lo < hi) {8 int mid = (lo + hi + ) / 2;9 if (a[mid] <= x) lo = mid;10 else hi = mid - 1;11 if (++rounds > 100) return -1;12 }13 return lo;14}15 16int main() {17 vector<int> a = {1, 3, 5, 5, 5, 8, 9};18 cout << last_le(a, 8) << " " << last_le(a, 5) << endl;19 return 0;20}
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.Binary search on the answer
Binary search isn't only for arrays. Whenever a problem can be put as: 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 what we want is the last k it holds for.
1#include <iostream>2using namespace std;3 4int main() {5 long long n = 2000000000; // 2 billion6 long long lo = 0, hi = n + 1; // look for the first k with k * k > n7 int rounds = 0;8 while (lo < hi) {9 long long mid = lo + (hi - lo) / 2;10 rounds++;11 if (mid * mid <= n) lo = mid + 1;12 else hi = mid;13 }14 cout << "sqrt(" << n << ") rounded down is " << lo - 1 << ", after " << rounds << " rounds" << endl;15 return 0;16}
sqrt(2000000000) rounded down is 44721, after 31 rounds
2 billion takes just 31 rounds. Note the long long: with mid near 2 billion, mid × mid overflows an int. Interview problems like "the least capacity", "the fewest days" or "the smallest maximum" are mostly binary search on 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, first make clear which one is wanted. When writing it, first decide whether the range is [lo, hi] or [lo, hi), then how each branch shrinks it, and last check whether it gets stuck with one or two elements left.
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, must be eaten within 8 hours; each hour you eat from one pile only, at speed k bananas an hour (a pile with fewer than k left still takes an hour). What's the smallest k? ok(k) is written; finish the binary search for the first k that makes ok true.
4
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> piles = {3, 6, 7, 11};6int h = 8;7 8bool ok(int k) { // can speed k finish within h hours?9 int hours = 0;10 for (int p : piles)11 hours += (p + k - 1) / k; // rounded up12 return hours <= h;13}14 15int main() {16 int lo = 1, hi = 11; // the answer is from 1 to 1117 // look for the first ok k: if ok(mid), hi = mid, otherwise lo = mid + 118 cout << lo << endl;19 return 0;20}
With the STL
The lower and upper written by hand in this lesson are in <algorithm>: lower_bound(b, e, x) and upper_bound(b, e, x), written just like ours (half-open, halving each time), except that they return iterators: subtract begin() for the index, and end() means "none". equal_range(b, e, x) gives you both at once, as a pair.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <functional>5using namespace std;6 7int main() {8 vector<int> a = {58, 60, 60, 72, 85, 85, 85, 91};9 auto lo = lower_bound(a.begin(), a.end(), 60);10 cout << "index of the first >= 60: " << lo - a.begin() << endl;11 auto r = equal_range(a.begin(), a.end(), 85); // a pair: first is lower, second is upper12 cout << "85 is in [" << r.first - a.begin() << ", " << r.second - a.begin()13 << "), " << r.second - r.first << " of them" << endl;14 cout << "the last <= 80 is " << *(upper_bound(a.begin(), a.end(), 80) - 1) << endl;15 16 a.insert(lower_bound(a.begin(), a.end(), 70), 70); // insert at the boundary: still sorted17 for (int x : a) cout << x << ' ';18 cout << endl;19 20 auto it = lower_bound(a.begin(), a.end(), 100);21 cout << (it == a.end() ? "nothing >= 100" : "something >= 100") << endl;22 23 vector<int> d = {9, 7, 5, 5, 3}; // sorted largest first24 auto p = lower_bound(d.begin(), d.end(), 5, greater<int>());25 cout << "sorted largest first, index of the first <= 5: " << p - d.begin() << endl;26 return 0;27}
index of the first >= 60: 1 85 is in [4, 7), 3 of them the last <= 80 is 72 58 60 60 70 72 85 85 85 91 nothing >= 100 sorted largest first, index of the first <= 5: 2
Before *(upper_bound(…) − 1), make sure upper_bound isn't begin(), or subtracting one goes out of range; here 80 is bigger than 58, so it's fine. When the array is sorted largest first, pass the same comparison greater<int>() too, and "the first not less than" becomes "the first not greater than".
a.insert(pos, 70) finds the place in O(log n), but inserting moves everything after it back one, O(n). When data is inserted and searched at the same time, use next lesson's set, which has its own member function s.lower_bound(x).
| Function | Returns | Time |
|---|---|---|
lower_bound(b, e, x) | an iterator to the first ≥ x | O(log n) |
upper_bound(b, e, x) | an iterator to the first > x | O(log n) |
equal_range(b, e, x) | both together, a pair | O(log n) |
upper − lower | how many x there are | O(log n) |
v.insert(lower_bound(…), x) | still sorted after inserting | O(n): it moves things |
In interviews: use lower_bound whenever you can, one less chance of an endless loop; when the interviewer wants it by hand, write the half-open template and say "left part < x, right part ≥ x, find the boundary". Two common traps: compare the iterator with end() before dereferencing it; on a set or map, use the member s.lower_bound(x), not std::lower_bound, which is O(n) on a tree.
What does each of the three iterators tell you? (e == a.end()) is a bool, which cout prints as 1 or 0.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> a = {10, 20, 20, 20, 30, 40};8 auto l = lower_bound(a.begin(), a.end(), 20);9 auto u = upper_bound(a.begin(), a.end(), 20);10 auto e = lower_bound(a.begin(), a.end(), 50);11 cout << l - a.begin() << " " << u - l << " " << (e == a.end()) << endl;12 return 0;13}
u - l subtracts two iterators, giving how many lie between them, which is the number of 20s: 3. 50 is bigger than everything, so lower_bound returns end(), the comparison holds and 1 is printed. The STL doesn't say "none" with -1; it uses end().set<int> s holds n numbers. Both of these lines find the first element ≥ x. How long does each take?
1auto p = s.lower_bound(x); // ①2auto q = lower_bound(s.begin(), s.end(), x); // ②
std::lower_bound wants to jump straight to the middle, but a set's iterator can only walk one step at a time (++), so reaching the middle takes n / 2 steps, O(n) in all. The member function s.lower_bound(x) follows the tree down, which is O(log n). The same goes for map.Summary
Binary search bounds: find the boundary
- Half-open [lo, hi): lo = 0, hi = n, go on while lo < hi; a[mid] < x gives lo = mid + 1, else hi = mid
- count = upper − lower; the last ≤ x = upper − 1
- The range must shrink every round: with lo = mid, round mid up
- Binary search on the answer: when "does it work" is monotonic, find the first that works
- STL: lower_bound / upper_bound / equal_range return iterators; compare with end() first
1auto it = lower_bound(a.begin(), a.end(), x);2if (it != a.end() && *it == x)3 cout << "the first x is at " << it - a.begin();4int cnt = upper_bound(a.begin(), a.end(), x)5 - lower_bound(a.begin(), a.end(), x);