Complexity Analysis

Reason about how running time and memory grow with input size using Big-O, Theta and Omega, amortized analysis and recursion recurrences.

Beginner · about 6 hours · difficulty 2/5

Complexity analysis lets you predict whether a solution will pass before you write it. Interviewers expect you to state time and space complexity for every solution you propose.

The notations

  • Big-O is an upper bound on growth, Omega a lower bound, Theta a tight bound. In interviews "O" is used loosely to mean the tight worst case.
  • Drop constants and lower-order terms: 3n^2 + 5n is O(n^2).
  • Common classes in order: O(1), O(log n), O(n), O(n log n), O(n^2), O(2^n), O(n!).

Estimating from constraints

A typical judge does roughly 10^8 simple operations per second. So:

  • n <= 10^5 or 10^6: aim for O(n) or O(n log n).
  • n <= 5000: O(n^2) is fine.
  • n <= 20: exponential like O(2^n) or bitmask DP is acceptable.

Reading constraints this way is one of the most useful habits you can build.

Beyond simple loops

  • Amortized cost: a dynamic array doubles its capacity occasionally, but push_back is O(1) amortized because the total copying work over n pushes is O(n).
  • Recurrences: merge sort is T(n) = 2T(n/2) + O(n) = O(n log n). Learn the Master Theorem intuition rather than memorizing cases.
  • Space: count auxiliary memory, including the recursion stack. A recursive DFS on a path-shaped tree uses O(n) stack.

Pitfalls

Hidden costs: string concatenation in a loop, substr/slicing (O(k)), and list.pop(0). Nested loops are not always O(n^2): the two-pointer pattern moves each pointer at most n times, so it is O(n).

Key concepts

  • Big-O, Omega and Theta
  • Best, average and worst case
  • Estimating from constraints: About 1e8 ops per second
  • Space complexity and call stack
  • Amortized analysis: Dynamic array doubling
  • Recurrences and Master Theorem
  • Harmonic series O(n log n) loops

Mini project

Take 10 short code snippets (nested loops, halving loops, recursion like fib and merge sort, sieve-style j += i loops) and write their time and space complexity with a one-line justification; then time a O(n^2) and O(n log n) solution on n = 10^5 to see the difference.

Check yourself

The loop 'for i in 1..n: for j = i; j <= n; j += i' looks nested. What is its actual complexity and why?

Free resources