Counting the steps
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.
find_max(a, 10000000)about 2 s9 999 999 comparisonsfind_max(a, 10000000)about 0.2 s9 999 999 comparisonsSo 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.
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";⑥
- ①once
- ②once: only at the start
- ③n + 1 times: true for i = 0 to 4, false at i = 5, which ends the loop
- ④n times
- ⑤n times: this is the basic operation
- ⑥once
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".
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".
i1int best = a[0];2for (int i = 1; i < n; i++)3 if (a[i] > best)4 best = a[i];
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:
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}
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.
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 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}
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:
i↑j1for (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;
For every step of the outer loop, the inner loop runs through the rest. The simplest form runs both loops all n times:
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}
You check 10 numbers for repeats by comparing every pair once. If there are no repeats at all, how many comparisons does it take?
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.
10
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}
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:
for (i = 0; i < n; i++)64 timesn timesfor (i = 0; i < n; i += 2)32 timesn / 2 times: still grows with nfor (i = 1; i < n; i *= 2)6 timesgrows very slowly: the log n of lesson 3- 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.
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}
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.
6
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}
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:
Once n is large, those odd steps stop mattering:
| n | 3n + 2 | n² | time for 3n + 2 | time for n² |
|---|---|---|---|---|
| 10 | 32 | 100 | under 1 µs | 1 µs |
| 1 000 | 3 002 | 1 000 000 | 30 µs | 0.01 s |
| 1 000 000 | 3 000 002 | 1 000 000 000 000 | 0.03 s | about 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".
Two pieces of code take these many steps: A takes 100n, B takes n². For n = 1 million, which is faster?
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.
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}
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.
| Code | What it does inside | Steps |
|---|---|---|
max_element(b, e), min_element(b, e) | one pass, each compared with the largest (smallest) so far | n − 1 comparisons |
find(b, e, x) | compares from the start, stops when found | at most n |
count(b, e, x) | one pass, compares every one | n |
accumulate(b, e, 0) (<numeric>) | one pass, adds every one | n 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.
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++;
find compares from the start of a, all n of them when the number isn't there. That one line of find hides a loop, and inside the outer loop it makes n × n.Summary
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