Big O Notation
An upper bound on how cost grows as input grows. It deliberately discards constants, because the constant stops mattering once the input is large enough.
What the Notation Says
Big O notation describes how an algorithm's cost grows as its input grows. Writing O(n²) says the running time grows no faster than the square of the input size, up to a constant factor. It is one of three forms of asymptotic notation, the other two being Omega and Theta.
Formally, f(n) = O(g(n)) if there exist constants c > 0 and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀. The n₀ is what makes the notation asymptotic: behaviour on small inputs is explicitly ignored.
The imprecision is the point. An algorithm taking 3n² + 50n + 1000 steps is O(n²): with c = 4 the inequality 3n² + 50n + 1000 ≤ 4n² reduces to n² − 50n − 1000 ≥ 0, which first holds at n₀ = 66 (at n = 65, 16,925 > 16,900) and holds for every larger n. The exact constant tells you about one machine; the class tells you about all of them.
- O(1) does not mean fast – it means the cost does not grow with n; a constant 10-second step is still O(1)
- The log base does not matter – log₂n and log₁₀n differ by a constant factor (about 3.32), so both are O(log n)
- It bounds memory too – the same notation describes extra space, not only time
Big O vs Omega vs Theta
- O(g) – grows at most as fast as g. Upper bound.
- Ω(g) – grows at least as fast as g. Lower bound.
- Θ(g) – grows exactly as fast as g. Both bounds.
- Case – worst, average or best, a separate question from the bound.
Three notations bound growth in different directions, and mixing them up is the most common mistake.
Big O is the upper bound: cost grows at most this fast. Omega (Ω) is the lower bound: at least this fast. Theta (Θ) applies when both hold at the same rate, which is the tightest and most informative statement.
Because O is only an upper bound, O(n²) is technically true of a linear algorithm. It is correct and useless, like saying a journey takes under a year. In practice O is written where Θ is meant, which is harmless as long as the bound is tight.
A separate question is which case is described. Worst, average and best case are questions about the input; O, Ω and Θ are questions about the bound. Quicksort is Θ(n log n) in the average case and Θ(n²) in the worst: both are Theta statements about different cases.
- Ω formally – f(n) ≥ c·g(n) for all n ≥ n₀, with c > 0
- Θ formally – c₁·g(n) ≤ f(n) ≤ c₂·g(n) for all n ≥ n₀; two constants, one on each side
- Little o and little ω – the strict versions: n = o(n²), but n² is not o(n²)
The Common Growth Classes
A handful of classes cover almost everything, and the gaps between them are enormous.
O(1) is constant: array indexing, a hash table lookup. O(log n) halves the problem each step: binary search, balanced tree operations. O(n) touches each element once. O(n log n) is the best a comparison sort can do: merge sort, heapsort.
O(n²) is nested iteration over the input, typical of comparing every pair. O(2ⁿ) and O(n!) are the combinatorial classes, usable only on tiny inputs or when memoization collapses the recursion.
The gaps are worth feeling in real numbers. At n = 1,000,000: log n is 20, n log n is 20 million, and n² is a trillion. On a machine doing a billion operations a second, that is 20 nanoseconds, 20 milliseconds and about 17 minutes.
- O(1) < O(log n) < O(√n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!)
- O(√n) – trial division tests divisors only up to √n
- O(n!) – trying every ordering; 10! is 3,628,800 and 20! is about 2.4 × 10¹⁸
Terms, operations, and practical uses
Core vocabulary
- O(g)Upper bound: f(n) ≤ c·g(n) for all n ≥ n₀.
- Ω(g)Lower bound: f(n) ≥ c·g(n) for all n ≥ n₀.
- Θ(g)Both bounds hold, with possibly different constants. The tight statement.
- n₀The threshold after which the bound must hold. Below it, anything goes.
- Dominant termThe fastest-growing term of f(n); the one the bound keeps.
Growth at n = 10, 1,000 and 10⁶
- O(1)1 · 1 · 1
- O(log n)≈ 3 · ≈ 10 · ≈ 20
- O(n)10 · 1,000 · 10⁶
- O(n log n)≈ 33 · ≈ 10⁴ · ≈ 2 × 10⁷
- O(n²)100 · 10⁶ · 10¹²
- O(2ⁿ)1,024 · ≈ 10³⁰¹ · beyond counting; hopeless past n ≈ 50
Related lessons and problems
- Time and Space ComplexityApplying the notation to running time and memory.
- Amortized AnalysisBounding the average cost per operation over a sequence.
- Recurrence RelationsGetting the class of recursive code.
- P, NP, NP-Complete and NP-HardWhat polynomial time buys, and the problems that seem to lack it.
- Merge SortO(n log n), and the constants that make insertion sort win on small inputs.
Code in Python, C++ and Java
import math
SIZES = [10, 100, 1_000, 1_000_000]
OPS_PER_SECOND = 1e9
def classes(n):
return {
"O(1)": 1,
"O(log n)": math.log2(n),
"O(n)": n,
"O(n log n)": n * math.log2(n),
"O(n^2)": n * n,
}
def human(seconds):
if seconds < 1e-6:
return f"{seconds * 1e9:.0f} ns"
if seconds < 1e-3:
return f"{seconds * 1e6:.0f} us"
if seconds < 1:
return f"{seconds * 1e3:.0f} ms"
if seconds < 60:
return f"{seconds:.0f} s"
return f"{seconds / 60:.0f} mins"
def count_steps(n):
"""The worked example: one pass, then a triangle of nested steps."""
count = 0
for i in range(n):
count += 1
for i in range(n):
for j in range(i, n):
count += 1
return count
def smallest_n0(f, bound, limit=200):
"""Smallest n0 with f(n) <= bound(n) for every n from n0 up to limit.
A finite check only; the algebra in the lesson proves it for all larger n.
"""
failures = [n for n in range(1, limit) if f(n) > bound(n)]
return failures[-1] + 1 if failures else 1
def simplify(terms):
"""Drop constants, keep the dominant term - the whole of Big O in one line."""
return max(terms, key=lambda t: t[1])[0]
def main():
counts = ", ".join(f"n={n} -> {count_steps(n)}" for n in (4, 8, 16))
print(f"count_steps: {counts}")
n0 = smallest_n0(count_steps, lambda n: n * n)
print(f"f(n) = (n^2 + 3n)/2 <= 1*n^2 from n0 = {n0} -> O(n^2)\n")
header = "n".rjust(10) + "".join(name.rjust(14) for name in classes(10))
print(header)
for n in SIZES:
row = f"{n:>10,}"
for _, steps in classes(n).items():
row += human(steps / OPS_PER_SECOND).rjust(14)
print(row)
print("\nsimplifying 3n^2 + 50n + 1000:")
terms = [("n^2", 2), ("n", 1), ("1", 0)] # (name, degree)
print(f" dominant term -> O({simplify(terms)})")
n0 = smallest_n0(lambda n: 3 * n * n + 50 * n + 1000, lambda n: 4 * n * n)
print(f" 3n^2 + 50n + 1000 <= 4n^2 from n0 = {n0}")
if __name__ == "__main__":
main()#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
constexpr double OPS_PER_SECOND = 1e9;
std::vector<std::pair<std::string, double>> classes(double n) {
return {
{"O(1)", 1.0},
{"O(log n)", std::log2(n)},
{"O(n)", n},
{"O(n log n)", n * std::log2(n)},
{"O(n^2)", n * n},
};
}
std::string human(double seconds) {
char buf[64];
if (seconds < 1e-6) std::snprintf(buf, sizeof buf, "%.0f ns", seconds * 1e9);
else if (seconds < 1e-3) std::snprintf(buf, sizeof buf, "%.0f us", seconds * 1e6);
else if (seconds < 1) std::snprintf(buf, sizeof buf, "%.0f ms", seconds * 1e3);
else if (seconds < 60) std::snprintf(buf, sizeof buf, "%.0f s", seconds);
else std::snprintf(buf, sizeof buf, "%.0f mins", seconds / 60);
return buf;
}
std::string commas(long n) {
std::string s = std::to_string(n);
for (int i = static_cast<int>(s.size()) - 3; i > 0; i -= 3) s.insert(i, ",");
return s;
}
// The worked example: one pass, then a triangle of nested steps.
long countSteps(long n) {
long count = 0;
for (long i = 0; i < n; i++) count++;
for (long i = 0; i < n; i++) {
for (long j = i; j < n; j++) count++;
}
return count;
}
// Smallest n0 with f(n) <= bound(n) for every n from n0 up to 200.
// A finite check only; the algebra in the lesson proves it for larger n.
long smallestN0(const std::function<long(long)>& f, const std::function<long(long)>& bound) {
long n0 = 1;
for (long n = 1; n < 200; n++) if (f(n) > bound(n)) n0 = n + 1;
return n0;
}
// Drop constants, keep the dominant term - the whole of Big O in one line.
std::string simplify(const std::vector<std::pair<std::string, int>>& terms) {
std::string best = terms.front().first;
int bestDegree = terms.front().second;
for (const auto& [name, degree] : terms) {
if (degree > bestDegree) { best = name; bestDegree = degree; }
}
return best;
}
int main() {
std::cout << "count_steps: n=4 -> " << countSteps(4) << ", n=8 -> " << countSteps(8)
<< ", n=16 -> " << countSteps(16) << "\n";
std::cout << "f(n) = (n^2 + 3n)/2 <= 1*n^2 from n0 = "
<< smallestN0(countSteps, [](long n) { return n * n; }) << " -> O(n^2)\n\n";
std::cout << std::setw(10) << "n";
for (const auto& [name, _] : classes(10)) std::cout << std::setw(14) << name;
std::cout << "\n";
for (long n : {10L, 100L, 1000L, 1000000L}) {
std::cout << std::setw(10) << commas(n);
for (const auto& [_, steps] : classes(static_cast<double>(n))) {
std::cout << std::setw(14) << human(steps / OPS_PER_SECOND);
}
std::cout << "\n";
}
std::cout << "\nsimplifying 3n^2 + 50n + 1000:\n";
std::cout << " dominant term -> O(" << simplify({{"n^2", 2}, {"n", 1}, {"1", 0}}) << ")\n";
std::cout << " 3n^2 + 50n + 1000 <= 4n^2 from n0 = "
<< smallestN0([](long n) { return 3 * n * n + 50 * n + 1000; },
[](long n) { return 4 * n * n; }) << "\n";
return 0;
}import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.LongUnaryOperator;
public class Main {
private static final double OPS_PER_SECOND = 1e9;
private static Map<String, Double> classes(double n) {
Map<String, Double> m = new LinkedHashMap<>();
m.put("O(1)", 1.0);
m.put("O(log n)", Math.log(n) / Math.log(2));
m.put("O(n)", n);
m.put("O(n log n)", n * Math.log(n) / Math.log(2));
m.put("O(n^2)", n * n);
return m;
}
private static String human(double seconds) {
if (seconds < 1e-6) return String.format("%.0f ns", seconds * 1e9);
if (seconds < 1e-3) return String.format("%.0f us", seconds * 1e6);
if (seconds < 1) return String.format("%.0f ms", seconds * 1e3);
if (seconds < 60) return String.format("%.0f s", seconds);
return String.format("%.0f mins", seconds / 60);
}
// The worked example: one pass, then a triangle of nested steps.
static long countSteps(int n) {
long count = 0;
for (int i = 0; i < n; i++) count++;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) count++;
}
return count;
}
// Smallest n0 with f(n) <= bound(n) for every n from n0 up to 200.
// A finite check only; the algebra in the lesson proves it for larger n.
static long smallestN0(LongUnaryOperator f, LongUnaryOperator bound) {
long n0 = 1;
for (long n = 1; n < 200; n++) if (f.applyAsLong(n) > bound.applyAsLong(n)) n0 = n + 1;
return n0;
}
// Drop constants, keep the dominant term - the whole of Big O in one line.
private static String simplify(String[] names, int[] degrees) {
String best = names[0];
int bestDegree = degrees[0];
for (int i = 1; i < names.length; i++) {
if (degrees[i] > bestDegree) { best = names[i]; bestDegree = degrees[i]; }
}
return best;
}
public static void main(String[] args) {
System.out.printf("count_steps: n=4 -> %d, n=8 -> %d, n=16 -> %d%n",
countSteps(4), countSteps(8), countSteps(16));
System.out.printf("f(n) = (n^2 + 3n)/2 <= 1*n^2 from n0 = %d -> O(n^2)%n%n",
smallestN0(n -> countSteps((int) n), n -> n * n));
StringBuilder header = new StringBuilder(String.format("%10s", "n"));
for (String name : classes(10).keySet()) header.append(String.format("%14s", name));
System.out.println(header);
for (long n : new long[] {10L, 100L, 1000L, 1000000L}) {
StringBuilder row = new StringBuilder(String.format("%,10d", n));
for (double steps : classes(n).values()) {
row.append(String.format("%14s", human(steps / OPS_PER_SECOND)));
}
System.out.println(row);
}
System.out.println("\nsimplifying 3n^2 + 50n + 1000:");
System.out.printf(" dominant term -> O(%s)%n",
simplify(new String[] {"n^2", "n", "1"}, new int[] {2, 1, 0}));
System.out.printf(" 3n^2 + 50n + 1000 <= 4n^2 from n0 = %d%n",
smallestN0(n -> 3 * n * n + 50 * n + 1000, n -> 4 * n * n));
}
}Step through it
Running on count_steps(n) at n = 4, 8 and 16; growth classes at n = 100 and 1,000,000
Rules for Simplifying
- Drop constant factors –
O(3n)isO(n); a constant multiple does not change the growth rate. - Keep only the dominant term –
O(n² + n)isO(n²); for large n the smaller term is a vanishing fraction. - Sequential code adds – two loops one after another are
O(n) + O(n) = O(n). - Nested code multiplies – a loop inside a loop is
O(n) × O(n) = O(n²).
Reducing an expression to its class follows a few mechanical rules, applied in order.
One caution: dropping constants is a claim about large inputs. An O(n log n) algorithm with a large constant can lose to an O(n²) one on small inputs, which is why real sort implementations switch to insertion sort below a threshold of roughly 16 to 64 elements. The step-by-step demo shows the crossover.
- Different inputs keep their own letters – a loop over n items inside a loop over m items is O(n·m), not O(n²)
- Adding a bigger class absorbs the smaller – O(n) + O(n log n) = O(n log n)
- Constants inside a power or exponent stay – 2²ⁿ = 4ⁿ is not O(2ⁿ)
How to Find the Big O of Code
- Single loop over n →
O(n). - Nested loops, both over n →
O(n²); multiply the bounds. - Counter doubling or halving →
O(log n). - Loop inside a halving loop →
O(n log n). - Recursion → write the recurrence, then solve it.
- Fixed bound, however large →
O(1)for that loop.
The rules simplify an expression once you have one. Getting it from actual code is the part exams test, and it comes down to counting how many times the innermost statement runs.
Nested loops multiply only when the inner bound really is n. A loop running n, n−1, n−2 … 1 executes n(n+1)/2 times, which is still O(n²), while an inner loop with a fixed bound of 100 stays O(n). The demo counts one such function exactly: a pass of n plus a triangle of n(n+1)/2 gives 14, 44 and 152 steps at n = 4, 8 and 16, which is f(n) = (n² + 3n)/2, O(n²) with c = 1, n₀ = 3.
A loop whose counter is multiplied or divided each round is O(log n), because reaching n from 1 by doubling takes log₂n steps. That is why binary search is logarithmic.
Recursion needs its recurrence solved. One call on half the input is T(n) = T(n/2) + O(1), giving O(log n). Two calls on halves plus linear merging is T(n) = 2T(n/2) + O(n), giving O(n log n). Two calls on n−1 is T(n) = 2T(n−1), giving O(2ⁿ). Recurrence relations covers the solving methods.
- Loops that stop at √n –
for (i = 1; i * i <= n; i++)runs about √n times, so O(√n) - Hidden work in one line –
s = s + con an immutable string copies s, so doing it n times is O(n²); a sort call inside a loop costs O(n log n) per round - Early exits do not change the worst case – a loop that can break at the first match is still O(n) when the match is last or missing