Complexity Analysis & Big-O

How to measure an algorithm's efficiency independent of hardware — Big-O, Θ and Ω, common classes, amortized and space complexity.

Beginner 4 min readLesson 1 of 18 Interview Q&A

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.

input size n →operations →O(1)O(log n)O(n)O(n log n)O(n²)O(2ⁿ)
How runtime grows with input size n

Big-O, Big-Θ, Big-Ω

NotationMeaningAnalogy
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

  1. Drop constants: O(3n + 5) → O(n). Constants depend on hardware; growth doesn't.
  2. Keep the dominant term: O(n² + n log n + 1000) → O(n²).
  3. Sequential steps add: a loop over n then a loop over m → O(n + m).
  4. Nested steps multiply: a loop over n containing a loop over m → O(n·m).
  5. Different inputs get different variables. Don't call it O(n²) if it's really O(n·m).

Common complexity classes

ClassNameExamplen = 1,000,000
O(1)ConstantArray index, hash lookup1
O(log n)LogarithmicBinary search, balanced BST~20
O(n)LinearSingle scan, counting10⁶
O(n log n)LinearithmicMerge sort, heap sort2 × 10⁷
O(n²)QuadraticNested loops, bubble sort10¹² — too slow
O(2ⁿ)ExponentialAll subsetsimpossible
O(n!)FactorialAll permutationsimpossible

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)

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.

Key takeaways
  • 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.
Interview questions
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.