Big-O notation describes how an algorithm's running time or memory grows as the input grows, ignoring machine speed and constant factors. It lets you compare algorithms on paper, predict whether a solution will finish in time before writing it, and discuss performance in a shared vocabulary. O gives an upper bound, Ω a lower bound and Θ a tight bound.
Think of it like
Moving house: carry or rent a truck?
Carrying boxes by hand takes about the same time per box, so the total grows linearly with the number of boxes. Renting a truck costs a fixed two hours of paperwork and driving, almost regardless of how many boxes fit. For three boxes, carrying wins. For three thousand, the truck wins by a mile. Big-O ignores the paperwork and asks only how each plan scales as the pile grows.
Why count growth, not seconds
Wall-clock time depends on the CPU, the language, the compiler and even what else the machine is doing. Instead we count basic operations (comparisons, assignments, arithmetic) as a function of the input size n, written T(n). Then we keep only the part that dominates as n becomes large.
def sum_and_pairs(a):
total = 0
for x in a: # runs n times
total += x
pairs = 0
for i in range(len(a)): # runs n times
for j in range(len(a)): # ... n times each
pairs += 1
return total, pairs
# T(n) = n + n^2 + c -> O(n^2)For n = 1,000 the quadratic part does a million steps while the linear part does a thousand. As n grows, the n² term is all that matters, so we say the function is O(n²). The visualization above plots common growth curves side by side so you can see how quickly they separate.
Formal definitions
Each notation describes a set of functions. Writing f(n) = O(g(n)) really means f belongs to the set of functions that grow no faster than g, up to a constant factor, once n is large enough.
| Notation | Reads as | Analogy with numbers | Example |
|---|---|---|---|
f = O(g) | f grows no faster than g | f ≤ g | 3n + 5 = O(n), and also = O(n²) |
f = Ω(g) | f grows at least as fast as g | f ≥ g | n² = Ω(n log n) |
f = Θ(g) | f grows exactly like g | f = g | n²/2 − 3n = Θ(n²) |
f = o(g) | f grows strictly slower than g | f < g | n log n = o(n²), but n ≠ o(n) |
f = ω(g) | f grows strictly faster than g | f > g | 2ⁿ = ω(n¹⁰⁰) |
Proving a bound: a worked example
Claim: f(n) = 3n² + 10n + 5 is Θ(n²). For the upper bound we need constants c and n₀. For every n ≥ 1 we have 10n ≤ 10n² and 5 ≤ 5n², so each term can be bounded by a multiple of n².
Simplification rules
| Rule | Statement | Example |
|---|---|---|
| Drop constant factors | O(c · f(n)) = O(f(n)) for any constant c > 0 | 5n + 3 is O(n) |
| Drop lower-order terms | O(f + g) = O(max(f, g)) | n² + n log n + 7 is O(n²) |
| Sum rule (sequential code) | O(f) then O(g) costs O(f + g) | Loop over n, then loop over m: O(n + m) |
| Product rule (nested code) | O(f) work repeated O(g) times costs O(f · g) | For each of n items, scan m items: O(n · m) |
| Log bases do not matter | log_a n = log_b n / log_b a, a constant factor | log₂ n, ln n and log₁₀ n are all O(log n) |
| Polynomials | A degree-k polynomial with positive leading coefficient is Θ(nᵏ) | 4n³ − 2n² + 9 is Θ(n³) |
| Exponent bases do matter | 2ⁿ and 3ⁿ differ by the factor 1.5ⁿ, which is not constant | 3ⁿ is not O(2ⁿ) |
Sum rule: one after another
for x in a: ...thenfor y in b: ...- Costs add: O(n + m)
- If n = m, that is O(2n) = O(n)
- The larger term dominates the total
Product rule: one inside another
for x in a: for y in b: ...- Costs multiply: O(n · m)
- If n = m, that is O(n²)
- Nesting is where most slow code comes from
Common complexity classes
| Class | Name | Typical example |
|---|---|---|
| O(1) | Constant | Array indexing, hash map lookup (average), push onto a stack |
| O(log n) | Logarithmic | Binary Search, balanced BST lookup, fast exponentiation |
| O(√n) | Square root | Trial-division primality test |
| O(n) | Linear | One pass over the input, Linear Search, counting frequencies |
| O(n log n) | Linearithmic | Merge Sort, Heap Sort, sorting in general |
| O(n²) | Quadratic | All pairs, Bubble Sort, Insertion Sort worst case |
| O(n³) | Cubic | Floyd-Warshall, naive matrix multiplication |
| O(2ⁿ) | Exponential | All subsets of a set, naive recursive Fibonacci |
| O(n!) | Factorial | All permutations, brute-force traveling salesman |
| n | log₂ n | n log₂ n | n² | 2ⁿ |
|---|---|---|---|---|
| 10 | 3.3 | 33 | 100 | 1,024 |
| 20 | 4.3 | 86 | 400 | ~1.0 × 10⁶ |
| 100 | 6.6 | 664 | 10,000 | ~1.3 × 10³⁰ |
| 1,000 | 10 | ~10⁴ | 10⁶ | ~1.1 × 10³⁰¹ |
| 10⁶ | 20 | ~2 × 10⁷ | 10¹² | unimaginable |
Will it run in time? The feasibility table
A practical rule of thumb: a compiled language (C++, Java, Go, Rust) performs roughly 10⁸ simple operations per second. Python is often 10 to 50 times slower for plain loops. Multiply your complexity by the input size and compare against that budget before you write any code.
| Complexity | n = 10 | n = 10³ | n = 10⁵ | n = 10⁶ | n = 10⁹ |
|---|---|---|---|---|---|
| O(log n) | Yes | Yes | Yes | Yes | Yes (~30 ops) |
| O(√n) | Yes | Yes | Yes | Yes | Yes (~3 × 10⁴) |
| O(n) | Yes | Yes | Yes | Yes | Borderline (10⁹, ~10 s) |
| O(n log n) | Yes | Yes | Yes (~1.7 × 10⁶) | Yes (~2 × 10⁷) | No (~3 × 10¹⁰) |
| O(n²) | Yes | Yes (10⁶) | No (10¹⁰) | No (10¹²) | No |
| O(n³) | Yes | Borderline (10⁹) | No | No | No |
| O(2ⁿ) | Yes (~10³) | No | No | No | No |
| O(n!) | Yes (~3.6 × 10⁶) | No | No | No | No |
Best, average and worst case vs upper and lower bounds
These are two independent ideas that people constantly mix up. A case fixes which inputs you analyze. A bound (O, Ω, Θ) describes how tightly you describe the resulting cost function. You can give an O, Ω or Θ bound for any case.
Cases: which input?
- Best case: the cheapest input of size n
- Worst case: the most expensive input of size n
- Average case: expected cost under a stated input distribution
- Each case is its own function of n
Bounds: how tight?
- O: the function grows no faster than this
- Ω: the function grows at least this fast
- Θ: both at once, the exact growth rate
- Applies to any of the case functions
| Algorithm | Best case | Average case | Worst case |
|---|---|---|---|
| Linear Search | Θ(1): target is first | Θ(n): about n/2 checks | Θ(n): target missing |
| Binary Search | Θ(1): middle element | Θ(log n) | Θ(log n) |
| Insertion Sort | Θ(n): already sorted | Θ(n²) | Θ(n²): reverse sorted |
| Quick Sort | Θ(n log n) | Θ(n log n) | Θ(n²): bad pivots every time |
| Hash table lookup | Θ(1) | Θ(1) with a good hash | Θ(n): every key collides |
Lower bounds can also describe a problem rather than an algorithm. Any comparison-based sort must make Ω(n log n) comparisons in the worst case, so merge sort is optimal among comparison sorts, and beating that bound requires a different model, such as Counting & Bucket Sort.
Space complexity
The same notation measures memory. Auxiliary space is the extra memory beyond the input; that is what people usually mean by "O(1) space". Recursion counts too: each active call holds a stack frame, so a recursion of depth n uses O(n) space even if it allocates nothing else. Time & Space Complexity Analysis covers this in depth.
Asymptotics in practice
- Constants still matter for real inputs. An O(n log n) algorithm with a tiny constant can beat an O(n) one with a huge constant for every input you will ever see.
- Small n favors simple code. Production sorts (Timsort, introsort) switch to Insertion Sort for runs of about 16 to 64 elements because it is faster at that size despite being O(n²).
- Memory access patterns matter. Scanning an array is far faster than chasing linked-list pointers, though both are O(n), because of CPU caches.
- Big-O is about the trend. Use it to rule out hopeless approaches and compare scalable ones, then measure.
Complexity
| Class | Name | Typical example | Ops at n = 10⁶ |
|---|---|---|---|
| O(1) | Constant | Array index, hash lookup | 1 |
| O(log n) | Logarithmic | Binary search | ~20 |
| O(√n) | Square root | Trial division | 1,000 |
| O(n) | Linear | Single pass | 10⁶ |
| O(n log n) | Linearithmic | Merge sort | ~2 × 10⁷ |
| O(n²) | Quadratic | All pairs | 10¹² |
| O(2ⁿ) | Exponential | All subsets | Infeasible past n ≈ 30 |
| O(n!) | Factorial | All permutations | Infeasible past n ≈ 12 |
At about 10⁸ simple operations per second, anything above ~10⁸ total operations is unlikely to finish within a typical one-second limit.
Implementation
Small, recognizable shapes for the most common classes. Learn to spot these loop shapes and you can estimate most code at a glance.
def constant(a: list[int]) -> int:
"""O(1): one step no matter how long the list is."""
return a[0]
def logarithmic(n: int) -> int:
"""O(log n): halve the problem each step."""
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
def linear(a: list[int]) -> int:
"""O(n): touch every element once."""
best = a[0]
for x in a:
best = max(best, x)
return best
def linearithmic(a: list[int]) -> list[int]:
"""O(n log n): comparison sorting."""
return sorted(a)
def quadratic(a: list[int]) -> int:
"""O(n^2): look at every pair."""
count = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
if a[i] + a[j] == 0:
count += 1
return count
def exponential(a: list[int], target: int, i: int = 0) -> bool:
"""O(2^n): try including or excluding every element (subset sum)."""
if i == len(a):
return target == 0
return exponential(a, target - a[i], i + 1) or exponential(a, target, i + 1)Key takeaways
- Big-O describes growth rate as n becomes large, ignoring constant factors and lower-order terms.
- O is an upper bound, Ω a lower bound, Θ a tight bound, and little-o a strictly-smaller bound.
- Sequential code adds costs (sum rule); nested code multiplies them (product rule). Use separate variables for separate inputs.
- Memorize the ladder O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ) < O(n!) and the budget of about 10⁸ simple operations per second.
- Best, average and worst case choose the input; O, Ω and Θ choose how tightly you bound it. They are independent.
Common pitfalls
- Equating Big-O with worst case. Big-O is an upper bound and can be applied to any case.
- Writing O(n²) for two different inputs that should be O(n · m), or O(n) for two sequential loops over different inputs that should be O(n + m).
- Keeping constants or lower-order terms ("O(2n + 5)"), which is not wrong but signals unfamiliarity.
- Assuming library calls are O(1):
list.index,x in list, string concatenation in a loop andsubstringcan all be O(n). - Believing a better Big-O is always faster in practice for small inputs; constants and cache behavior matter.
Interview tips
- State complexity unprompted for every solution, naming each variable you use.
- If asked "can you do better?", compare your bound with the input size and the obvious lower bound (you must at least read the input, so Ω(n)).
- Use the feasibility table aloud: "n is up to 10⁵, so O(n²) is 10¹⁰ operations, too slow; I'll aim for O(n log n)."
Real-world applications
- Predicting whether a solution meets a time limit before writing it.
- Capacity planning: estimating how latency changes when data grows 10×.
- Choosing between data structures (hash map vs sorted array vs tree) by their operation costs.
- Spotting accidental quadratic behavior in code reviews.
Practice problems
Test yourself
What is the simplest tight bound for T(n) = 4n² + 100·n log n + 7?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.