Kodewick
Start learning →
Big O: O(1), O(n), O(n²)2 / 52

Big O: O(1), O(n), O(n²)

Lesson 2 of 52 · Part 1 · Getting started: how fast · about 17 minutes

Big O says how fast the steps grow with n: drop the constants and smaller terms and keep the fastest-growing one, so 3n + 2 is O(n), two nested loops are O(n²), and v[i] is O(1).

The last lesson counted steps: finding the largest is about n steps, two nested loops about n². Big O is the short way to say that: O(n), O(n²). It doesn't care whether it's 3n + 2 or 5n, only about how it grows.

Common kinds of growth: O(1) stays flat, O(log n) grows very slowly, O(n) is a straight line, O(n log n) a little faster, O(n²) shoots up

What Big O says

Writing Big O takes two moves:

  1. Drop the constants: 3n and n are both O(n). Constants only change things by a fixed factor; the growth is the same.
  2. Keep only the biggest term: n² + 100n + 7 is O(n²). Once n is large, the rest is negligible.

So 3n + 2 is O(n), n²/2 + n/2 is O(n²), and 20 is O(1).

Choose one

What is 3n² + 5n + 100 in Big O?

O(1): nothing to do with n

Reading one element of a vector by index takes one step to work out the address (the start + i × the size of an element) and one to read it, however long the vector is.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a(100000);7    a[99999] = 42;8    // however long a is, a[i] is this one step9    cout << a[99999] << "\n";10    cout << a.size() << "\n";   // size() is O(1) too: the vector keeps its length11    return 0;12}
Output
42
100000

Swapping two variables, working out an expression, a return: all O(1), a fixed number of steps.

a4927501234↑i

Reading a[3]: the start address plus the size of 3 elements gives its place at once, no counting from the front
Choose one

n is the length of the array. Which piece of code is O(1)?

O(n): one pass

To find a number in an array, in the worst case you look from the first to the last.

a (looking for x = 7)4925701234↑i
1for (int i = 0; i < n; i++)2    if (a[i] == x)3        return i;4return -1;

Linear search for 7: in the worst case n looks, O(n)

One loop whose body is O(1) is O(n) overall.

Choose one

An O(n) program takes 1 millisecond for n = 1000. About how long does it take for n = 4000?

O(n²): two nested loops

To ask "does the array have a repeated number", the most direct way is to compare every pair:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5bool has_dup(const vector<int>& a) {6    int n = a.size();7    for (int i = 0; i < n; i++)8        for (int j = i + 1; j < n; j++)9            if (a[i] == a[j])10                return true;11    return false;12}13 14int main() {15    vector<int> a = {3, 8, 1, 9, 8};16    cout << boolalpha << has_dup(a) << "\n";17    return 0;18}
Output
true

(boolalpha makes cout print a bool as true / false rather than 1 / 0.)

Guess the outputA wrong guess is fine

The inner loop only goes up to i. With n = 6, what does it print?

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

An O(n²) program takes 1 second for n = 1000. About how long does it take when n becomes 2000?

Exercise 1

Any repeats?

Complete has_dup: compare every pair with two nested loops, return true if some number repeats and false if not. Make the program print the two lines below.

It should print
true
false
exercise1.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5bool has_dup(const vector<int>& a) {6    int n = a.size();7    // compare every pair8    return false;9}10 11int main() {12    vector<int> a = {3, 8, 1, 9, 8};13    vector<int> b = {3, 8, 1, 9, 7};14    cout << boolalpha << has_dup(a) << "\n" << has_dup(b) << "\n";15    return 0;16}
Output
Press Run or Ctrl+Enter

Reading Big O off the code

You don't have to count every time. Three rules:

The code looks likeBig OWhy
One part after another (a loop, then another loop)the biggest partO(n) + O(n) is still O(n); O(n) + O(n²) is O(n²)
A loop inside a loopmultiplyn outer × n inner = O(n²)
Halve the size each timeO(log n)the next lesson

In an exam: for "find the time complexity", find how many times the innermost statement runs, write it as a formula in n, then drop the constants and small terms.

int cnt = 0;①for (int i = 0; i < n; i++)②    for (int j = 0; j < n; j++)③        if (a[i] == a[j]) cnt++;④for (int k = 0; k < n; k++)⑤    sum += a[k];
  1. ①outside the loops, once: O(1), ignore it
  2. ②outer loop: i from 0 to n − 1, n times
  3. ③for each outer round, the inner loop runs n times
  4. ④the innermost statement: n × n = n² times
  5. ⑤the part after it: n times, added to the two loops
Reading code this way: two nested loops, n × n, then one more loop, n: n² + n in all, keep the largest term: O(n²)
Choose one

What's the Big O of this code?

1for (int i = 0; i < n; i++)2    for (int j = 0; j < n; j++)3        for (int k = 0; k < n; k++)4            cnt++;
Choose one

There is only one loop. What is its Big O?

1for (int i = 0; i < n * n; i++)2    cnt++;
Exercise 2

One part after another

First a loop of n steps, then two nested loops of n × n steps. Complete the counting and print the total for n = 10.

It should print
110
exercise2.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int n = 10, steps = 0;6    for (int i = 0; i < n; i++)7        steps++;8    // now two nested loops, n times each, adding 1 to steps each time9    cout << steps << "\n";10    return 0;11}
Output
Press Run or Ctrl+Enter

Best, worst and average

The same code can take a different number of steps on different data. Take linear search: if the number you want is the first one, one look and you are done; if it is the last one, or not there at all, you have to look at all n.

best: find 4search(a, 4)1 lookit's the first one
worst: find 6search(a, 6)5 looksonly after looking at all of them do you know it's not there
The same linear search, looking for different numbers in the 5 numbers 4 9 2 5 7
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int looks = 0;6 7int search(const vector<int>& a, int x) {8    for (int i = 0; i < (int)a.size(); i++) {9        looks++;10        if (a[i] == x) return i;11    }12    return -1;13}14 15int main() {16    vector<int> a = {4, 9, 2, 5, 7};17    for (int x : {4, 2, 6}) {18        looks = 0;19        int at = search(a, x);20        cout << "find " << x << ": index " << at << ", " << looks << " looks\n";21    }22    return 0;23}
Output
find 4: index 0, 1 looks
find 2: index 2, 3 looks
find 6: index -1, 5 looks
  • Best case: the data that takes the fewest steps. For linear search that is 1 look, O(1).
  • Worst case: the data that takes the most steps. For linear search that is n looks, O(n).
  • Average case: if the number is equally likely to be at any position, it takes (1 + 2 + … + n) / n = (n + 1) / 2 looks on average: still O(n).

When people say "linear search is O(n)", they mean the worst case: however unlucky you are, it is never slower than that. If a question doesn't say which case, answer for the worst one.

Guess the outputA wrong guess is fine

Checking for repeats by comparing every pair once, stopping as soon as one is found. How many comparisons for these numbers?

1#include <iostream>2using namespace std;3 4int main() {5    int a[] = {5, 5, 1, 9, 3};6    int n = 5, cmp = 0;7    bool found = false;8    for (int i = 0; i < n && !found; i++)9        for (int j = i + 1; j < n && !found; j++) {10            cmp++;11            if (a[i] == a[j]) found = true;12        }13    cout << cmp << "\n";14    return 0;15}
Choose one

Linear search over n numbers; the number you want is definitely in the array and equally likely to be at any position. How many comparisons does it take on average?

With the STL

When counting "the innermost statement", count the loops hidden in the STL too. find(b, e, x) compares from the start until it finds x, count(b, e, x) compares every element: both O(n). Their versions with a condition, find_if and count_if, take a lambda, which is just right for counting the comparisons.

This "any repeats?" has only one loop, but every round calls count_if:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {3, 8, 1, 9, 7};8    int steps = 0;9    bool dup = false;10    for (int x : a) {11        int c = count_if(a.begin(), a.end(), [&](int y) {12            steps++;             // one count for every element count_if looks at13            return y == x;14        });15        if (c > 1) dup = true;16    }17    cout << boolalpha << dup << "\n";18    cout << "comparisons: " << steps << "\n";19    return 0;20}
Output
false
comparisons: 25

5 numbers, 25 comparisons: n times outside, n times inside count_if, n × n = O(n²), the same as two for loops. Shorter code, no less work.

CodeCostWhy
a[i], a.size(), a.back()O(1)work out an address, read the stored length
find(b, e, x), find_ifO(n)compares from the start, all of them in the worst case
count(b, e, x), count_ifO(n)compares every one
find / count inside a loopO(n²)n times × n each

In interviews: "what is the complexity of this code" often tests exactly this: a find, count or erase hidden in a loop turns O(n) into O(n²). Point out that line, then say how to fix it (sort first, or use an unordered_set, coming in later chapters).

Guess the outputA wrong guess is fine

A single for calls count_if, and the lambda counts the comparisons. What does it print?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {2, 7, 2, 5};8    int steps = 0, dup = 0;9    for (int x : a) {10        int c = count_if(a.begin(), a.end(), [&](int y) {11            steps++;12            return y == x;13        });14        if (c > 1) dup++;15    }16    cout << dup << " " << steps << "\n";17    return 0;18}

Summary

Take-away

Big O: drop the constants, keep only the fastest-growing term

  • O(1): a fixed number of steps; O(n): one pass; O(n²): two nested loops
  • One part after another: take the biggest; a loop in a loop: multiply
  • In an exam: count how many times the innermost statement runs
  • A find or count inside a loop is a loop too
  • Best, worst and average can differ; if nobody says which, it's the worst case
1a[i];                               // O(1)2for (int i = 0; i < n; i++) ...     // O(n)3for (...) for (...) ...             // O(n²)4for (int x : a) count(b, e, x);     // O(n²) too