Why count instead of time
A stopwatch measures your code, your hardware, your compiler, the data you happened to use and whatever else the machine was doing. Useful, but it does not tell you what happens when the input is a thousand times larger. Counting does.
Pick:
- a basic operation: something that takes roughly constant time and dominates the work, such as a comparison, an element write, or a loop iteration;
- an input size n: the length of the array, the number of nodes, the number of bits.
Then express the count as a function of n. The lab above counts comparisons and iterations for binary search; the linear search lab counts comparisons for the left-to-right scan. On the 64 values, worst case preset binary search runs 7 iterations, ⌊log₂ 64⌋ + 1. A linear scan that does not find the target compares all 64. At a million elements those numbers become 20 and 1,000,000. The linear vs binary search comparison puts the two side by side.
From an exact count to a growth class
Exact counts are often easy to get and awkward to compare:
| Code shape | Exact count | Growth class | Exercise |
|---|---|---|---|
| one loop over n items | n | Θ(n) | single loop |
| two loops in sequence | 2n | Θ(n) | sequential loops |
| loop stepping by 3 | ⌈n/3⌉ | Θ(n) | step three |
| inner loop runs i times | n(n − 1)/2 | Θ(n²) | triangular loop |
| halve until 1 | ⌊log₂ n⌋ | Θ(log n) | halving loop |
| loop while i² ≤ n | ⌊√n⌋ | Θ(√n) | square-root loop |
| n times a doubling loop | n · ⌈log₂ n⌉ | Θ(n log n) | loop times log |
| three nested loops | n³ | Θ(n³) | triple nested |
Two simplifications produce the right-hand column:
- Keep only the fastest-growing term. n(n − 1)/2 = n²/2 − n/2. For n = 1,000 the n²/2 term is 500,000 and the n/2 term is 500; the second barely matters and matters less as n grows.
- Drop the constant factor. n²/2 and n² differ by a factor that does not depend on n. Machines, compilers and languages change constant factors; they do not change the shape of the curve.
Every exercise page draws the measured count next to the scaled reference curve, so you can see the ratio settle to a constant.
O, Ω and Θ, precisely
For functions f and g of n (counts are non-negative):
- f(n) = O(g(n)) if there are constants c > 0 and n₀ such that f(n) ≤ c · g(n) for every n ≥ n₀. An upper bound: f grows no faster than g.
- f(n) = Ω(g(n)) if there are constants c > 0 and n₀ such that f(n) ≥ c · g(n) for every n ≥ n₀. A lower bound: f grows at least as fast as g.
- f(n) = Θ(g(n)) if both hold. A tight bound: f grows exactly like g, up to constant factors.
Example. f(n) = 3n² + 5n + 2. For n ≥ 1, 5n ≤ 5n² and 2 ≤ 2n², so f(n) ≤ 10n²: f = O(n²) with c = 10, n₀ = 1. Also f(n) ≥ 3n² for every n ≥ 0: f = Ω(n²) with c = 3. Therefore f = Θ(n²).
Three consequences people often get wrong:
- O is only an upper bound. Linear search is O(n), and it is also O(n²) and O(2ⁿ), which are true and useless. When someone writes "binary search is O(log n)" they nearly always mean the tight bound Θ(log n) for the worst case.
- O, Ω and Θ are not best, worst and average case. Those are different questions. Each case is a function of n, and each of those functions has its own O, Ω and Θ. "The worst case of linear search is Θ(n) and the best case is Θ(1)" is a precise sentence; the next lesson is about the cases.
- The
=is a convention, read as "is in the set". O(n) = n is not a valid statement.
The growth classes
| Class | Name | n = 10 | n = 1,000 | n = 1,000,000 | Typical source |
|---|---|---|---|---|---|
| Θ(1) | constant | 1 | 1 | 1 | array index, hash lookup (expected) |
| Θ(log n) | logarithmic | ≈ 3.3 | ≈ 10 | ≈ 20 | binary search, balanced tree, heap push |
| Θ(n) | linear | 10 | 1,000 | 10⁶ | one pass |
| Θ(n log n) | linearithmic | ≈ 33 | ≈ 10⁴ | ≈ 2 × 10⁷ | merge sort, heap sort |
| Θ(n²) | quadratic | 100 | 10⁶ | 10¹² | all pairs, insertion sort worst case |
| Θ(n³) | cubic | 1,000 | 10⁹ | 10¹⁸ | naive matrix multiplication |
| Θ(2ⁿ) | exponential | 1,024 | ≈ 10³⁰¹ | — | every subset |
| Θ(n!) | factorial | 3,628,800 | ≈ 4 × 10²⁵⁶⁷ | — | every ordering |
The Big O explorer draws these curves for n up to 64. Turn on the logarithmic y-axis to see them all at once; with a linear axis, 2ⁿ and n! leave the chart almost immediately. The exercises all subsets and all permutations show where the last two rows come from.
The base of a logarithm does not matter inside O: log₂ n = log₁₀ n / log₁₀ 2, a constant factor. That is why we write O(log n) without a base. (A base inside an exponent does matter: 2ⁿ and 3ⁿ are different classes.)
Rules for loops
- Sequential blocks add. Θ(n) followed by Θ(n²) is Θ(n + n²) = Θ(n²): the larger term wins.
- Nested loops multiply, when the inner count does not depend on the outer variable. n iterations of a Θ(log n) body cost Θ(n log n).
- When the inner count depends on the outer variable, sum it. The triangular loop sums to n(n − 1)/2. The shrinking inner loop sums n + n/2 + n/4 + … < 2n, so two nested loops cost only Θ(n). The harmonic loop sums n/i over i and gets Θ(n log n).
- How fast the loop variable moves decides the count. Adding a constant gives Θ(n) iterations; multiplying or dividing by a constant gives Θ(log n); see doubling a counter.
- A
breakhelps only if you can bound where it fires. The nested loop with a break is still Θ(n²). - Recursion: count calls times work per call, or write a recurrence. The recursive halving and divide and conquer exercises introduce the idea; module M29 covers recurrences in depth.
What Big O hides
- Constant factors. An algorithm doing 100n operations loses to one doing n² for every n < 100. Several standard-library sorts switch to insertion sort for short ranges for exactly this reason (see elementary sorts).
- Small inputs. Growth classes describe large n. For n = 20 almost anything is fast.
- Memory effects. Two Θ(n) traversals can differ by an order of magnitude because one reads contiguous memory and the other chases pointers; the contiguous storage lesson shows why.
- The cost of a "basic" operation. Comparing two integers is O(1); comparing two strings of length L is O(L). Sorting n strings is O(n log n) comparisons, which is O(L · n log n) character comparisons in the worst case.
Language notes: operations that look O(1) but are not
| Language | Looks cheap | Actual cost |
|---|---|---|
| C# | items.Count() (LINQ) on an IEnumerable<T> |
O(1) when the source implements ICollection<T>, otherwise it enumerates everything: O(n) |
| C# | list.Contains(x), list.Insert(0, x) |
O(n) |
| Python | x in some_list, some_list.index(x) |
O(n); x in some_set is O(1) on average |
| Python | some_list.pop(0), some_list.insert(0, x) |
O(n): every element shifts. collections.deque.popleft() is O(1) |
| Python | s = s + "x" in a loop |
copies the string each time; see string concatenation |
| Java | linkedList.get(i) |
O(n): it walks from the nearer end |
| Java | arrayList.add(0, x), arrayList.remove(0) |
O(n) |
| C++ | std::distance(first, last) |
O(1) for random-access iterators, linear otherwise |
| C++ | v.insert(v.begin(), x) on a std::vector |
O(n) |
Two that are cheaper than people expect: Python's len() is O(1) for built-in containers, and C++
std::list::size() is constant time since C++11.
Common mistakes
- Multiplying sequential loops (two loops in a row are 2n, not n²) or adding nested ones.
- Calling a loop logarithmic because it skips elements. Skipping a constant fraction is still linear; only geometric shrinking is logarithmic.
- Dropping a term that depends on a different input. Θ(n + m) is not Θ(n) unless m ≤ c · n; see the third lesson of this module.
- Treating O as "exactly". "Quicksort is O(n²)" is true for its worst case and also an upper bound for every case; say Θ when you mean tight.
- Ignoring hidden costs inside a line of code, such as
in,Contains, slicing or string+.
Worked practice
1. Show that 4n + 100 = Θ(n) by giving the constants.
Upper: for n ≥ 100, 100 ≤ n, so 4n + 100 ≤ 5n (c = 5, n₀ = 100). Lower: 4n + 100 ≥ 4n for all n ≥ 0 (c = 4). Both hold, so Θ(n).
2. A loop runs for i in range(n): for j in range(i, n): work(). What is the class?
The inner loop runs n − i times: n + (n − 1) + … + 1 = n(n + 1)/2. Θ(n²). It is the triangular loop mirrored.
3. Is n² = O(n³)? Is n³ = O(n²)?
n² = O(n³) is true (with c = 1, n₀ = 1), though not tight. n³ = O(n²) is false: n³ / n² = n grows without bound, so no constant c works.
4. Binary search on one billion sorted values: at most how many iterations?
⌊log₂ 10⁹⌋ + 1 = 29 + 1 = 30 (2²⁹ ≈ 5.4 × 10⁸ ≤ 10⁹ < 2³⁰ ≈ 1.07 × 10⁹).
Summary
- Choose a basic operation and an input size; count the operation as a function of n.
- Keep the leading term and drop its constant: that is the growth class.
- O is an upper bound, Ω a lower bound, Θ both; none of them means "worst case".
- Sequential code adds, independent nested loops multiply, dependent loops must be summed, and the speed of the loop variable decides linear versus logarithmic.
- Big O hides constants, small-n behaviour, memory effects and the cost of operations that look like one step. Check the docs for what each language's operations really cost.