Skip to content

Big O Notation: Upper Bound for Machine Learning Code

Big O notation describes how a cost grows as the input gets large, as an upper bound, and it deliberately ignores constant factors and small inputs. Lehman, Leighton, and Meyer, in Mathematics for Computer Science, say "Big Oh" is "the most frequently used asymptotic notation. It is used to give an upper bound on the growth of a function, such as the running time of an algorithm." Their standard definition (Definition 14.7.9): f(x) = O(g(x)) if there exist a constant c ≥ 0 and an x₀ such that for all x ≥ x₀, |f(x)| ≤ c·g(x). In their plain words, f(x) is less than or equal to g(x), "except that we're willing to ignore a constant factor, namely c, and to allow exceptions for small x, namely, for x < x₀."

Try it by hand. Say an algorithm takes T(n) = 3n² + 10n + 7 steps on n items. Claim: T(n) = O(n²). To prove it, choose a constant c and a threshold n₀. Try c = 4. We need 3n² + 10n + 7 ≤ 4n², which means n² − 10n − 7 ≥ 0, true for n ≥ 10.66. So take n₀ = 11. Check: at n = 11, T = 363 + 110 + 7 = 480 and 4n² = 484, so 480 ≤ 484. At n = 10, T = 407 and 4n² = 400, so the bound fails there, which is why the threshold matters. For every n ≥ 11 it holds. The book proves the same kind of fact for x² + 100x + 10 = O(x²).

Now the warning. Big O is an upper bound, so it can be loose: the book points out that 2x = O(x) even though 2x is not asymptotically equal to x and is not o(x), so Big O does not capture tightness. In the same way, T(n) above is also O(n³), which is true and tells you much less. And Big O is not a stopwatch. Compare an algorithm that takes 1000n steps with one that takes n² steps. The first is O(n) and the second is O(n²), yet at n = 100 the first costs 100,000 steps and the second 10,000. They break even at n = 1000 (1,000,000 steps each) and only past that does the O(n) algorithm win. For these two exact cost functions the crossover is at n = 1000 and the O(n) algorithm wins after it. But Big O alone does not say which of two algorithms is faster, because an upper bound can be loose: an algorithm that takes n steps is O(n), and one that takes a single step is also O(n²), yet the single-step algorithm wins for every n > 1. Tight bounds, written Θ, are the notation for saying how the cost really grows. Big O says how fast a cost can grow at most, not who wins on the data you have. The constants and examples here are invented.

The trap: reading Big O as an exact running time or as a tight bound. It says the cost grows no faster than a constant times g(x), from some size onward, and it says nothing about the constant or about small inputs.

Prof Rod's rule: use Big O to compare how methods scale, and a benchmark on your real data to compare how they run.

Lehman, Leighton, and Meyer, Mathematics for Computer Science (MIT 6.042, 2018), Section 14.7.2, Definition 14.7.9 and Proposition 14.7.11, pp. 631–632