Kodewick
Start learning →
Where log n comes from3 / 52

Where log n comes from

Lesson 3 of 52 · Part 1 · Getting started: how fast · about 16 minutes

O(log n) comes from halving the range at every step: guessing a number from 1 to 100 takes at most 7 tries, and binary search and the STL's lower_bound work the same way.

Guess a number from 1 to 100, and after each guess you are told "too high" or "too low". The smart way is to guess the middle every time: 50, then 25 or 75… and 7 guesses are always enough. 100 numbers, 7 steps: that is log n.

Halving every time

Each guess leaves half as many possibilities: 100 → 50 → 25 → 13 → 7 → 4 → 2 → 1. The number of halvings from n down to 1 is log₂ n.

1024 halved 10 times down to 1: each bar is half the one above it, and counting them gives 10, which is log₂ 1024
main.cpp
1#include <iostream>2using namespace std;3 4int halvings(int n) {5    int steps = 0;6    while (n > 1) {7        n /= 2;8        steps++;9    }10    return steps;11}12 13int main() {14    int sizes[] = {8, 100, 1000, 1000000};15    for (int n : sizes)16        cout << "n = " << n << "  halved " << halvings(n) << " times\n";17    return 0;18}
Output
n = 8  halved 3 times
n = 100  halved 6 times
n = 1000  halved 9 times
n = 1000000  halved 19 times

n grows from 1000 to a million (1000 times), and the steps only from 9 to 19 (10 more). That is what makes O(log n) so strong.

nlog₂ n (about)
1 00010
1 000 00020
1 000 000 00030
Choose one

An O(log n) algorithm takes about 10 steps for n = 1000. About how many does it take when n becomes 2000?

Exercise 1

How many halvings to reach 1

Complete the loop: halve n each time (integer division) until it is no longer greater than 1, and count the halvings for n = 1000.

It should print
9
exercise1.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int n = 1000, steps = 0;6    // inside a while: halve n, add 1 to steps7    cout << steps << "\n";8    return 0;9}
Output
Press Run or Ctrl+Enter

Doubling every time is log n too

Turn it around: starting from 1 and doubling, how many doublings until you reach n? The same number as halving n down to 1. When a loop variable is multiplied each time (rather than added to), the loop is log n.

Guess the outputA wrong guess is fine

i doubles every time. With n = 100, what does it print?

1#include <iostream>2using namespace std;3 4int main() {5    int n = 100, steps = 0;6    for (int i = 1; i < n; i *= 2)7        steps++;8    cout << steps << "\n";9    return 0;10}

Multiplying by 3 or by 10 is log n as well, only with a different base: log₃ n and log₂ n differ by a fixed factor, and Big O drops constants, so the base isn't written: it is just O(log n).

Binary search

In a sorted array you can search the same way: look at the middle element; if it is smaller than what you want, search only the right half; if it is bigger, only the left half.

a (looking for x = 9)1357911130123456↑lo↑hi
1int lo = 0, hi = n - 1;2while (lo <= hi) {3    int mid = (lo + hi) / 2;4    if (a[mid] == x) return mid;5    if (a[mid] < x) lo = mid + 1;6    else hi = mid - 1;7}8return -1;

Finding 9 among 7 numbers: look at the middle, throw away the half it can't be in, found in 3 looks
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int binary_find(const vector<int>& a, int x, int& steps) {6    int lo = 0, hi = (int)a.size() - 1;7    while (lo <= hi) {8        int mid = (lo + hi) / 2;9        steps++;10        if (a[mid] == x) return mid;11        if (a[mid] < x) lo = mid + 1;12        else hi = mid - 1;13    }14    return -1;15}16 17int main() {18    vector<int> a(1000);19    for (int i = 0; i < 1000; i++)20        a[i] = 2 * i;   // 0 2 4 … 1998, sorted21    int steps = 0;22    int at = binary_find(a, 1234, steps);23    cout << "1234 is at index " << at << ", found in " << steps << " looks\n";24    return 0;25}
Output
1234 is at index 617, found in 10 looks

1000 numbers take at most 10 looks. A linear search takes 1000 in the worst case.

It needs: a sorted array. Unsorted, the half you throw away might hold the number you want.

A common exam question: binary search on n elements makes at most ⌊log₂ n⌋ + 1 comparisons when the search succeeds (at most 4 for 10 elements).

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

Fill in the blank so that binary search finds 11 and prints its index, 5.

1#include <iostream>2using namespace std;3 4int main() {5    int a[] = {1, 3, 5, 7, 9, 11, 13};6    int lo = 0, hi = 6, x = 11, at = -1;7    while (lo <= hi) {8        int mid = (lo + hi) / 2;9        if (a[mid] == x) { at = mid; break; }10        if (a[mid] < x) lo = ;11        else hi = mid - 1;12    }13    cout << at << "\n";14    return 0;15}
Choose one

At most how many looks does binary search need on 1000 sorted numbers?

Exercise 2

Write binary search

Complete binary_find: look for x in the sorted a; return its index if found, -1 if not.

It should print
5
-1
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int binary_find(const vector<int>& a, int x) {6    int lo = 0, hi = (int)a.size() - 1;7    // while (lo <= hi): look at the middle, then drop half8    return -1;9}10 11int main() {12    vector<int> a = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};13    cout << binary_find(a, 23) << "\n";14    cout << binary_find(a, 7) << "\n";15    return 0;16}
Output
Press Run or Ctrl+Enter

Spotting log n in code

To tell whether a loop is log n, look at how the loop variable changes each time:

  • it adds or subtracts a number (i++, i += 2, i--): the runs are proportional to n, so it is O(n);
  • it multiplies or divides by a number (i *= 2, n /= 2, i *= 3): it is done in a few steps, so it is O(log n).
add 2 each timefor (i = 0; i < n; i += 2)512 timesO(n): just half as many
double each timefor (i = 1; i < n; i *= 2)10 timesO(log n)
n = 1024: adding 2 takes 512 runs, doubling only 10

Put one inside the other: the outer loop runs n times and the inner one doubles each time, n × log n steps in all, written O(n log n). It's a bit slower than O(n) and far faster than O(n²); merge sort and heap sort, coming later, grow exactly like this.

main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int sizes[] = {8, 64, 1024};6    for (int n : sizes) {7        int steps = 0;8        for (int i = 0; i < n; i++)9            for (int j = 1; j < n; j *= 2)10                steps++;11        cout << "n = " << n << "  " << steps << " steps\n";12    }13    return 0;14}
Output
n = 8  24 steps
n = 64  384 steps
n = 1024  10240 steps

For n = 1024 that's 10240 steps; if both loops ran all n times, it would be 1024 × 1024, just over a million.

Choose one

Which piece of code is O(log n)?

Guess the outputA wrong guess is fine

The outer loop runs n times; the inner one doubles each time. What does it print?

1#include <iostream>2using namespace std;3 4int main() {5    int n = 32, steps = 0;6    for (int i = 0; i < n; i++)7        for (int j = 1; j < n; j *= 2)8            steps++;9    cout << steps << "\n";10    return 0;11}

With the STL

<algorithm> has binary search ready-made: binary_search(b, e, x) only answers whether x is there (a bool); lower_bound(b, e, x) returns the position (an iterator) of the first element not less than x. When x is missing it points exactly where x would be inserted, so it is the one used more. As in the first lesson, pass a comparison that counts, and compare with find_if, which looks from the start:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a(1000);8    for (int i = 0; i < 1000; i++)9        a[i] = 2 * i;   // 0 2 4 … 199810    int steps = 0;11    auto less_count = [&](int x, int y) { steps++; return x < y; };12 13    auto it = lower_bound(a.begin(), a.end(), 1234, less_count);14    cout << "lower_bound(1234): index " << (it - a.begin()) << ", comparisons " << steps << "\n";15 16    steps = 0;17    it = lower_bound(a.begin(), a.end(), 1235, less_count);18    cout << "lower_bound(1235): " << *it << ", index " << (it - a.begin()) << ", comparisons " << steps << "\n";19 20    steps = 0;21    it = find_if(a.begin(), a.end(), [&](int y) { steps++; return y == 1234; });22    cout << "find_if(1234): index " << (it - a.begin()) << ", comparisons " << steps << "\n";23 24    cout << boolalpha << binary_search(a.begin(), a.end(), 1234) << " "25         << binary_search(a.begin(), a.end(), 1235) << "\n";26    return 0;27}
Output
lower_bound(1234): index 617, comparisons 10
lower_bound(1235): 1236, index 618, comparisons 10
find_if(1234): index 617, comparisons 618
true false

1235 isn't in the array, and lower_bound stops at 1236: that is where 1235 would go. For the same 1234, searching from the start took 618 comparisons, binary search 10.

From the startfind_if(b, e, ...)618 comparisonsO(n)
Binary searchlower_bound(b, e, 1234)10 comparisonsO(log n)
Looking for 1234 among the 1000 sorted numbers 0, 2, 4, …, 1998
CodeReturnsCost
binary_search(b, e, x)whether x is there: true / falseO(log n)
lower_bound(b, e, x)the first position with a value ≥ xO(log n)
upper_bound(b, e, x)the first position with a value > xO(log n)
upper_bound − lower_boundhow many times x appearsO(log n)

They all need the range already sorted (one sort is O(n log n), in the last lesson of chapter 0). On unsorted data they still run, but the answer is wrong, with no error.

In interviews: for a binary search problem, first ask whether lower_bound or upper_bound does it: they save a lot of boundary fiddling. Be clear on the difference: lower_bound finds "≥ x", upper_bound finds "> x". On a set or map write s.lower_bound(x) (O(log n)); lower_bound(s.begin(), s.end(), x) steps along one element at a time and becomes O(n).

Guess the outputA wrong guess is fine

a holds three 3s. What does it print?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {1, 3, 3, 3, 5, 8};8    auto lo = lower_bound(a.begin(), a.end(), 3);9    auto hi = upper_bound(a.begin(), a.end(), 3);10    cout << (lo - a.begin()) << " " << (hi - a.begin()) << " " << (hi - lo) << "\n";11    return 0;12}
Choose one

s is a set<int> holding n numbers. Which of these searches is O(log n)?

Summary

Take-away

Halving every time is O(log n)

  • For n = a million, log₂ n is only about 20
  • Doubling every time and halving every time are both log n
  • Binary search only works on a sorted array
  • STL: lower_bound finds the first ≥ x, upper_bound the first > x
  • n outer runs with an inner loop that doubles: O(n log n)
1while (lo <= hi) {2    int mid = (lo + hi) / 2;3    if (a[mid] == x) return mid;4    if (a[mid] < x) lo = mid + 1; else hi = mid - 1;5}6auto it = lower_bound(a.begin(), a.end(), x);