Kodewick
Start learning →
Counting the steps1 / 52

Counting the steps

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

Counting steps compares code without a stopwatch: count the basic operations and see how the count grows with n; finding the largest of n numbers takes n − 1 comparisons, by hand or with max_element.

Two pieces of code both get the right answer. Which is faster? A stopwatch can't settle it: another computer, another compiler, -O2 on or off, and the result changes. In algorithms, "faster" means something else: how quickly the number of steps grows as the data gets bigger.

Why a stopwatch won't do

The same program can take 2 seconds on an old computer and 0.2 on a new one; with 10 numbers it finishes in a blink, with 10 million it may take a minute. We want a way to talk about speed that doesn't depend on the machine.

A 2016 laptopfind_max(a, 10000000)about 2 s9 999 999 comparisons
A desktop from this yearfind_max(a, 10000000)about 0.2 s9 999 999 comparisons
The same code on the same data (an illustration): the stopwatch differs 10×, the comparisons not by one

So we count steps: one comparison, one assignment, one addition, each is a step. The number of steps depends only on the algorithm and the amount of data, not on the computer.

Choose one

Leo's program takes 3 seconds on his computer; Mia's takes 1 second on hers. Can you say Mia's algorithm is faster?

Which step to count: the basic operation

A program assigns, compares, adds... Counting every kind of step is tedious. Usually you count just one: the statement that runs most often, called the basic operation. It normally sits in the innermost loop; every other statement runs about as often, or far less.

Take a plain summing loop and count every part of it for n = 5:

int sum = 0;①for (int i = 0②; i < n③; i++④)    sum += a[i];⑤cout << sum << "\n";⑥
  1. ①once
  2. ②once: only at the start
  3. ③n + 1 times: true for i = 0 to 4, false at i = 5, which ends the loop
  4. ④n times
  5. ⑤n times: this is the basic operation
  6. ⑥once
How often each part runs for n = 5: i < n is checked 6 times, the last check fails and the loop ends

Altogether that's 1 + 1 + (n + 1) + n + n + 1 = 3n + 4. What decides the speed is the n runs of sum += a[i]: make n 10 times bigger and the total grows about 10 times too. So in practice you count only the basic operation and say "this code takes about n steps".

Choose one

For n = 10, how many times is the condition i < n in for (int i = 0; i < n; i++) checked?

Counting: finding the largest

To find the largest of n numbers, start with the first and compare each one with "the largest so far".

a4927501234↑i
1int best = a[0];2for (int i = 1; i < n; i++)3    if (a[i] > best)4        best = a[i];

Finding the largest: every number gets a look, so n numbers take n − 1 comparisons

A counter, steps, counts the comparisons. Try a few sizes of n. steps is passed by reference (int& steps), so what the function adds goes into main's own variable:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int find_max(const vector<int>& a, int n, int& steps) {6    int best = a[0];7    for (int i = 1; i < n; i++) {8        steps++;             // one comparison9        if (a[i] > best)10            best = a[i];11    }12    return best;13}14 15int main() {16    vector<int> a(1000);17    for (int i = 0; i < 1000; i++)18        a[i] = (i * 37) % 101;19    int sizes[] = {10, 100, 1000};20    for (int n : sizes) {21        int steps = 0;22        find_max(a, n, steps);23        cout << "n = " << n << "  " << steps << " comparisons\n";24    }25    return 0;26}
Output
n = 10  9 comparisons
n = 100  99 comparisons
n = 1000  999 comparisons

When n grows 10 times, the comparisons grow about 10 times too: the steps grow along with n.

Guess the outputA wrong guess is fine

Finding the largest of 50 numbers; steps counts the comparisons. What does it print?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> a(50);7    int steps = 0;8    for (int i = 0; i < 50; i++)9        a[i] = i % 7;10    int best = a[0];11    for (int i = 1; i < 50; i++) {12        steps++;13        if (a[i] > best)14            best = a[i];15    }16    cout << best << " " << steps << "\n";17    return 0;18}
Change it

Change only the number in the green box so that the program prints 99.

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

Two nested loops

Another common shape is a loop inside a loop. Its most common use is to compare every pair once, for example to check whether an array has a repeated number:

a63810123↑i↑j
1for (int i = 0; i < n; i++)2    for (int j = i + 1; j < n; j++)3        if (a[i] == a[j]) return true;4return false;

Any repeats? Every pair is compared once: 4 numbers take 3 + 2 + 1 = 6 comparisons

For every step of the outer loop, the inner loop runs through the rest. The simplest form runs both loops all n times:

Guess the outputA wrong guess is fine

With n = 10, what does this print?

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

You check 10 numbers for repeats by comparing every pair once. If there are no repeats at all, how many comparisons does it take?

Exercise 1

Every pair once

n people, and every two of them shake hands once (each pair with i < j). Complete the loop and count the handshakes for n = 5.

It should print
10
exercise1.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int n = 5, steps = 0;6    for (int i = 0; i < n; i++) {7        // j starts at i + 1; count each pair once8    }9    cout << steps << "\n";10    return 0;11}
Output
Press Run or Ctrl+Enter

Counting other loops

Not every loop runs exactly n times. Before counting, check three things: where it starts, where it stops, and how much it changes each time. Here's n = 64:

add 1 each timefor (i = 0; i < n; i++)64 timesn times
add 2 each timefor (i = 0; i < n; i += 2)32 timesn / 2 times: still grows with n
double each timefor (i = 1; i < n; i *= 2)6 timesgrows very slowly: the log n of lesson 3
How many times three loops run for n = 64
  • Adding 2: only half the runs, n / 2. Make n 10 times bigger and the runs grow 10 times too: it grows like a single pass.
  • Doubling: 1, 2, 4, 8... it passes n in no time. n = 64 takes 6 runs; even n = 1 million takes only 20.
  • A fixed inner loop: for (j = 0; j < 3; j++) runs 3 times however big n is, so inside n outer runs it makes 3n in total. Two nested loops are not always n²: it depends on whether the inner loop grows with n.
Guess the outputA wrong guess is fine

The inner loop always runs 4 times. What does it print?

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

Doubling every time

i starts at 1 and doubles each time, until it is no longer less than n. Complete the loop and count the steps for n = 64.

It should print
6
exercise2.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int n = 64, steps = 0;6    int i = 1;7    // inside while (i < n): double i, add 1 to steps8    cout << steps << "\n";9    return 0;10}
Output
Press Run or Ctrl+Enter

Only the fastest-growing part counts

Write the steps as a formula in n: finding the largest is about n steps, two nested loops n² steps. Real code adds a few odd steps (setting up, the final return), say 3n + 2. For very small n, 3n + 2 is even bigger than n²; but past 3.6, n² overtakes it and pulls further and further ahead:

3n + 2 and n² drawn to scale: below n = 3.6 n² is smaller, past that point n² is always bigger, and the gap keeps widening

Once n is large, those odd steps stop mattering:

n3n + 2n²time for 3n + 2time for n²
1032100under 1 µs1 µs
1 0003 0021 000 00030 µs0.01 s
1 000 0003 000 0021 000 000 000 0000.03 sabout 2.8 hours

(The times assume 10⁸ steps a second, the usual rough figure in competitive programming; real speed depends on the machine and on what each step does, but the order of magnitude holds.)

With lots of data, the n² code is hundreds of thousands of times slower than the 3n + 2 code: one is done in 0.03 seconds, the other takes an afternoon. So when comparing algorithms we look only at the fastest-growing term, and ignore the constant in front and the small terms behind. The next lesson turns this into "Big O".

Choose one

Two pieces of code take these many steps: A takes 100n, B takes n². For n = 1 million, which is faster?

Choose one

The step count is 2n² + 30n + 500. For large n, which term decides the speed?

With the STL

In C++, finding the largest takes one line: *max_element(a.begin(), a.end()) (header <algorithm>). One line is not one step: inside, it runs the same loop as in the "finding the largest" level. You can count it: max_element takes a third argument that says "how to compare", and we pass a lambda that counts each time it is called.

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {4, 9, 2, 7, 5};8    int steps = 0;9    auto it = max_element(a.begin(), a.end(), [&](int x, int y) {10        steps++;             // count every comparison11        return x < y;12    });13    cout << "the largest is " << *it << ", at index " << (it - a.begin()) << "\n";14    cout << "comparisons: " << steps << "\n";15    return 0;16}
Output
the largest is 9, at index 1
comparisons: 4

5 numbers, 4 comparisons, exactly like the hand-written loop. max_element returns an iterator (the position of that element): *it reads the value, it - a.begin() gives the index. [&] lets the lambda change steps outside it. This trick, passing a comparison that counts, comes back often: sort, set and priority_queue can all be counted this way.

CodeWhat it does insideSteps
max_element(b, e), min_element(b, e)one pass, each compared with the largest (smallest) so farn − 1 comparisons
find(b, e, x)compares from the start, stops when foundat most n
count(b, e, x)one pass, compares every onen
accumulate(b, e, 0) (<numeric>)one pass, adds every onen additions

In interviews: one line of STL is not O(1). find, count and max_element are each a loop over the data; put one inside another loop and you have two nested loops, n² steps. When asked for the complexity, find these "hidden loops" first.

Choose one

a and b both hold n numbers. This code counts how many numbers of b are also in a. In the worst case, about how many comparisons does it make?

1int cnt = 0;2for (int x : b)3    if (find(a.begin(), a.end(), x) != a.end())4        cnt++;

Summary

Take-away

Compare speed by counting steps and watching them grow with n

  • A stopwatch measures the machine; counting steps measures the algorithm
  • One pass: about n steps; two nested loops: about n² steps
  • For large n, only the fastest-growing term matters
  • max_element, find and count are one pass too: one line, n steps
  • Adding 2 is still about n steps, doubling takes only log n; a fixed inner loop is not n²
1for (int i = 0; i < n; i++)         // about n steps2    for (int j = 0; j < n; j++)     // about n × n steps3        steps++;4max_element(a.begin(), a.end());    // also about n steps