Complexity Analysis & Big-O
How to measure an algorithm's efficiency independent of hardware — Big-O, Θ and Ω, common classes, amortized and space complexity.
Timing code with a stopwatch tells you how fast it ran on this machine, with this input, today. To compare algorithms we instead ask: how does the amount of work grow as the input size n grows? That growth rate is the algorithm's complexity.
Big-O, Big-Θ, Big-Ω
| Notation | Meaning | Analogy |
|---|---|---|
| O(g(n)) | Grows at most like g(n) — an upper bound | ≤ |
| Ω(g(n)) | Grows at least like g(n) — a lower bound | ≥ |
| Θ(g(n)) | Grows exactly like g(n) — tight bound | = |
Formally, f(n) = O(g(n)) if there exist constants c and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀. In everyday engineering, "Big-O" is used loosely to mean the tight bound.
The rules of thumb
- Drop constants: O(3n + 5) → O(n). Constants depend on hardware; growth doesn't.
- Keep the dominant term: O(n² + n log n + 1000) → O(n²).
- Sequential steps add: a loop over n then a loop over m → O(n + m).
- Nested steps multiply: a loop over n containing a loop over m → O(n·m).
- Different inputs get different variables. Don't call it O(n²) if it's really O(n·m).
Common complexity classes
| Class | Name | Example | n = 1,000,000 |
|---|---|---|---|
| O(1) | Constant | Array index, hash lookup | 1 |
| O(log n) | Logarithmic | Binary search, balanced BST | ~20 |
| O(n) | Linear | Single scan, counting | 10⁶ |
| O(n log n) | Linearithmic | Merge sort, heap sort | 2 × 10⁷ |
| O(n²) | Quadratic | Nested loops, bubble sort | 10¹² — too slow |
| O(2ⁿ) | Exponential | All subsets | impossible |
| O(n!) | Factorial | All permutations | impossible |
Analysing code
// O(n): one pass
int sum(int[] a) {
int s = 0;
for (int x : a) s += x;
return s;
}
// O(n²): every pair
int countPairs(int[] a) {
int c = 0;
for (int i = 0; i < a.length; i++)
for (int j = i + 1; j < a.length; j++) // n-1 + n-2 + ... + 1 = n(n-1)/2
if (a[i] + a[j] == 0) c++;
return c;
}
// O(log n): the problem halves each step
int halvings(int n) {
int steps = 0;
while (n > 1) { n /= 2; steps++; }
return steps;
}
// O(n log n): log n levels × O(n) work per level (e.g. merge sort)# O(n): one pass
def total(a):
s = 0
for x in a:
s += x
return s
# O(n²): every pair
def count_pairs(a):
c = 0
for i in range(len(a)):
for j in range(i + 1, len(a)): # n(n-1)/2 iterations
if a[i] + a[j] == 0:
c += 1
return c
# O(log n): halve each step
def halvings(n):
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
# Hidden costs: `x in some_list` is O(n); `x in some_set` is O(1); s[1:] copies O(n)// O(n): one pass
const sum = (a: number[]) => a.reduce((s, x) => s + x, 0);
// O(n²): every pair
function countPairs(a: number[]): number {
let c = 0;
for (let i = 0; i < a.length; i++)
for (let j = i + 1; j < a.length; j++)
if (a[i] + a[j] === 0) c++;
return c;
}
// O(log n)
function halvings(n: number): number {
let steps = 0;
while (n > 1) { n = Math.floor(n / 2); steps++; }
return steps;
}
// Hidden costs: arr.includes / indexOf / shift / splice are O(n)Recursive code
Write the recurrence and solve it:
T(n) = T(n/2) + O(1)→ O(log n) (binary search)T(n) = 2T(n/2) + O(n)→ O(n log n) (merge sort)T(n) = 2T(n−1) + O(1)→ O(2ⁿ) (naive Fibonacci-like branching)T(n) = T(n−1) + O(n)→ O(n²) (selection sort, unbalanced quicksort)
The master theorem solves T(n) = aT(n/b) + O(nᵈ) in one step — see Divide and conquer. For branching recursion, a useful estimate is O(branches^depth).
Space complexity
Count the extra memory the algorithm allocates, as a function of n: auxiliary arrays, hash maps, and recursion depth (each call uses a stack frame). Recursive DFS on a degenerate tree uses O(n) stack space even though it allocates nothing else.
Amortized analysis
Some operations are occasionally expensive but cheap on average over a sequence. Appending to a dynamic array is O(n) when it resizes, yet n appends cost O(n) total — so amortized O(1) per append. Other examples: hash-table resizing, Union-Find with path compression, the two-stack queue. Amortized is a guarantee over any sequence — not a probabilistic average.
- Complexity describes growth with input size, not wall-clock time.
- Drop constants and lower-order terms; add sequential parts, multiply nested parts.
- Know the ladder: 1 < log n < n < n log n < n² < 2ⁿ < n!.
- Count recursion depth in space complexity; watch out for hidden O(n) library calls.
- Amortized cost averages expensive operations over a sequence.
QWhat's the complexity of this: for i in 1..n, for j in i..n step i?medium
The inner loop runs n/i times, so the total is n(1 + 1/2 + 1/3 + … + 1/n) = n·Hₙ = O(n log n) — the harmonic series. This is the complexity of the Sieve of Eratosthenes-style loops.
QIs O(2ⁿ⁺¹) the same as O(2ⁿ)? What about O(2²ⁿ)?medium
2ⁿ⁺¹ = 2·2ⁿ, just a constant factor → O(2ⁿ). But 2²ⁿ = 4ⁿ, which is exponentially larger than 2ⁿ — a different class.
QWhy can an O(n log n) algorithm beat an O(n) one in practice?medium
Big-O hides constants and memory behaviour. An O(n) algorithm with a large constant, heavy allocation or poor cache locality can lose to a tight O(n log n) loop for realistic n. Always measure when it matters.