Kodewick
Start learning →
Binary search bounds and lower_bound38 / 52

Binary search bounds and lower_bound

Lesson 38 of 52 · Part 7 · Searching · about 17 minutes

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.
a (x = 5; the dashed cell at the end is index n = 7)135558901234567↑lo↑hi
1int 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;

Finding the first position ≥ 5 in 1 3 5 5 5 8 9: the range [lo, hi) halves each time, and where lo and hi finally meet is the boundary
Choose one

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 wantHow
the first ≥ xlower_bound(x)
the first > xupper_bound(x)
how many times x appearsupper_bound(x) − lower_bound(x)
the last ≤ xupper_bound(x) − 1
where x goes to keep things sortedlower_bound(x)
main.cpp
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}
Output
index of the first >= 60: 1
85 appears 3 times
the last <= 80 is 72
70 goes at index 3
Choose one

a = 1 3 3 3 5 8, x = 3. What are lower_bound(x) and upper_bound(x)?

Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

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.

It should print
3 5
-1 -1
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

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:

a (x = 8)13555890123456↑lo↑hi
1while (lo < hi) {2    int mid = (lo + hi) / 2;3    if (a[mid] <= x) lo = mid;      // the bug4    else hi = mid - 1;5}

The "lo = mid" version looking for the last ≤ 8: the first three rounds go fine; with two left, mid equals lo and the range never changes again
main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

lower_bound uses hi = mid. How must mid be worked out then?

Change it

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}
Should print
5 4

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.

main.cpp
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}
Output
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.

Choose one

What kind of problem allows binary search on the answer?

Choose one

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?

Exercise 2

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.

It should print
4
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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.

main.cpp
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}
Output
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).

FunctionReturnsTime
lower_bound(b, e, x)an iterator to the first ≥ xO(log n)
upper_bound(b, e, x)an iterator to the first > xO(log n)
equal_range(b, e, x)both together, a pairO(log n)
upper − lowerhow many x there areO(log n)
v.insert(lower_bound(…), x)still sorted after insertingO(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.

Guess the outputA wrong guess is fine

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}
Choose one

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);      // ②

Summary

Take-away

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);