Big-O Notation tells you how to describe growth; complexity analysis is the craft of deriving it from real code. This lesson turns loops, recursion and occasionally expensive operations into precise bounds: counting nested and dependent loops, solving recurrences with recursion trees, substitution and the Master Theorem, spreading costs with amortized analysis, and accounting for memory, including the call stack.
Think of it like
An accountant's audit
An auditor tallies every line item (each loop iteration), follows recurring commitments that spawn further commitments (recursive calls), and spreads a rare big purchase, like a new server every few years, across the months it serves (amortized cost). The goal is not the exact cent but a trustworthy total that tells you whether the budget will hold as the business grows.
Counting loops
For iterative code, the cost is the number of times the innermost statement runs. Find how many iterations each loop makes as a function of the enclosing loop variables, then add or multiply.
Sequential and nested loops
Loops one after another add (O(n) + O(m) = O(n + m)). A loop inside a loop multiplies when the inner range does not depend on the outer variable: n outer iterations times m inner iterations is O(n · m).
Dependent loops
When the inner bound depends on the outer variable, write the total as a sum and evaluate it. The classic "every pair i < j" loop runs 0 + 1 + 2 + … + (n − 1) times.
A subtler dependent loop steps the inner index by i. For each i the inner loop runs about n/i times, giving a harmonic series. This exact shape appears in the Sieve of Eratosthenes (see Math for DSA) and in many "for each divisor" problems.
Logarithmic loops
If the loop variable is multiplied or divided by a constant each step, it reaches its limit after a logarithmic number of steps: starting at 1 and doubling, after k steps it is 2ᵏ, which passes n when k = log₂ n.
| Loop shape | Iterations | Complexity |
|---|---|---|
for i in range(n) | n | O(n) |
for i in range(n): for j in range(n) | n² | O(n²) |
for i in range(n): for j in range(i) | n(n − 1)/2 | O(n²) |
i = 1; while i < n: i *= 2 | ⌈log₂ n⌉ | O(log n) |
i = 0; while i * i < n: i += 1 | ⌈√n⌉ | O(√n) |
i = 2; while i < n: i = i * i | about log₂ log₂ n | O(log log n) |
for i in range(1, n + 1): for j in range(0, n, i) | ≈ n ln n | O(n log n) |
for i in range(n): j = 1; while j < n: j *= 2 | n · log₂ n | O(n log n) |
i = n; while i > 0: (loop i times); i //= 2 | n + n/2 + n/4 + … < 2n | O(n) |
Recursion and recurrences
A recursive function's cost is described by a recurrence: the cost for size n equals the cost of its recursive calls plus the work it does itself. Write it as T(n) = (number of calls) × T(subproblem size) + (non-recursive work) and a base case such as T(1) = O(1).
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + O(1) | O(log n) |
| Factorial, linear recursion | T(n) = T(n − 1) + O(1) | O(n) |
| Tree traversal (balanced) | T(n) = 2T(n/2) + O(1) | O(n) |
| Merge sort | T(n) = 2T(n/2) + O(n) | O(n log n) |
| Quick sort, worst case | T(n) = T(n − 1) + O(n) | O(n²) |
| Naive Fibonacci | T(n) = T(n − 1) + T(n − 2) + O(1) | O(φⁿ) ≈ O(1.618ⁿ) |
| Tower of Hanoi | T(n) = 2T(n − 1) + O(1) | O(2ⁿ) |
| Karatsuba multiplication | T(n) = 3T(n/2) + O(n) | O(n^log₂3) ≈ O(n^1.585) |
The recursion tree method
- 1
Draw the tree
Each node is one call, labeled with the non-recursive work it does. Its children are the calls it makes.
- 2
Sum each level
Compute the total work across all nodes at depth
k. - 3
Count the levels
If the size shrinks by a factor
beach level, there are aboutlog_b nlevels; if it shrinks by 1, there aren. - 4
Add the levels
Sum the per-level totals. Often it is a constant per level, or a geometric series dominated by its first or last term.
Merge sort, T(n) = 2T(n/2) + cn: level k has 2ᵏ calls, each on n/2ᵏ elements doing c · n/2ᵏ work, so every level costs exactly cn. There are log₂ n + 1 levels.
Root-heavy: T(n) = 2T(n/2) + n²
- Level costs: n², n²/2, n²/4, …
- A decreasing geometric series
- The root dominates: Θ(n²)
Balanced: T(n) = 2T(n/2) + n
- Level costs: n, n, n, …
- log₂ n + 1 equal levels
- Total: Θ(n log n)
Leaf-heavy: T(n) = 3T(n/2) + n
- Level costs: n, 3n/2, 9n/4, …
- An increasing geometric series
- The 3^(log₂ n) = n^(log₂ 3) leaves dominate: Θ(n^1.585)
The substitution method
Guess the form of the answer, then prove it by induction. For T(n) = 2T(n/2) + n, guess T(n) ≤ c · n log₂ n and assume it holds for n/2.
The Master Theorem
Most divide-and-conquer recurrences have the form below: split into a subproblems of size n/b and do f(n) work to divide and combine. Compare f(n) with the critical exponent n^(log_b a), which is the total work done at the leaves.
| Case | Condition on f(n) | Result | Who dominates |
|---|---|---|---|
| 1 | f(n) = O(n^(log_b a − ε)) for some ε > 0 | T(n) = Θ(n^(log_b a)) | Leaves |
| 2 | f(n) = Θ(n^(log_b a) · logᵏ n) for some k ≥ 0 | T(n) = Θ(n^(log_b a) · log^(k+1) n) | Every level equally |
| 3 | f(n) = Ω(n^(log_b a + ε)) for some ε > 0, and a · f(n/b) ≤ c · f(n) for some c < 1 | T(n) = Θ(f(n)) | Root |
| Recurrence | a, b | n^(log_b a) | f(n) | Case | Result |
|---|---|---|---|---|---|
| T(n) = 8T(n/2) + n² | 8, 2 | n³ | n² | 1 | Θ(n³) |
| T(n) = 9T(n/3) + n | 9, 3 | n² | n | 1 | Θ(n²) |
| T(n) = T(n/2) + 1 (binary search) | 1, 2 | n⁰ = 1 | 1 | 2, k = 0 | Θ(log n) |
| T(n) = 2T(n/2) + n (merge sort) | 2, 2 | n | n | 2, k = 0 | Θ(n log n) |
| T(n) = 2T(n/2) + n log n | 2, 2 | n | n log n | 2, k = 1 | Θ(n log² n) |
| T(n) = 2T(n/2) + n² | 2, 2 | n | n² | 3 | Θ(n²) |
| T(n) = 3T(n/4) + n log n | 3, 4 | n^0.79 | n log n | 3 | Θ(n log n) |
Amortized analysis
Some operations are usually cheap but occasionally expensive. Amortized analysis bounds the total cost of any sequence of m operations and divides by m. Unlike average-case analysis there is no probability involved: the guarantee holds for the worst possible sequence.
The canonical example is appending to a dynamic array (see Arrays & Dynamic Arrays). When the array is full, allocate one twice as large and copy everything over. A single append can cost O(n), yet appends are O(1) amortized. Three standard methods prove it.
1. Aggregate method
Add up the real cost of n appends starting from an empty array. Each append writes one element, and resizes copy 1, 2, 4, … elements, a geometric series that sums to less than 2n.
2. Accounting (banker's) method
Charge every append 3 coins. One pays for writing the element; the other two are stored as credit. Just after a resize to capacity 2k has copied the k elements, the bank is empty apart from at most one spare coin left over from the very first appends. The next k appends deposit 2k coins, exactly enough to pay for copying all 2k elements at the next resize. The bank never goes negative, so 3 coins per append covers every cost.
3. Potential method
Define a potential function Φ on the data structure's state (stored-up "energy"), with Φ = 0 initially and Φ ≥ 0 always. The amortized cost of an operation is its real cost plus the change in potential.
- No resize: real cost 1, size grows by 1 so Φ rises by 2. Amortized cost
1 + 2 = 3. - Resize when size = capacity = k: real cost
k + 1(copy k, write 1). Before, Φ = 2k − k = k. After, size is k + 1 and capacity 2k, so Φ = 2. Amortized cost(k + 1) + (2 − k) = 3. - Starting from capacity 0, Φ stays non-negative because the array is always at least half full after the first append, so the total amortized cost bounds the total real cost.
| Method | Idea | Best for |
|---|---|---|
| Aggregate | Sum the cost of the whole sequence, divide by its length | Simple structures with one operation type |
| Accounting | Overcharge cheap operations, bank the surplus for expensive ones | Intuitive arguments with a few operation types |
| Potential | Encode the bank balance as a function Φ of the state | Complex structures (splay trees, Fibonacci heaps, union-find) |
Space complexity
- Input space
- Memory holding the input itself. Usually excluded when people say "O(1) space".
- Auxiliary space
- Extra memory the algorithm allocates: hash maps, copies, DP tables, queues.
- Call stack space
- One frame per active recursive call. A recursion of depth
dcosts O(d) space even if it allocates nothing else. - Output space
- Memory for the result. Generating all subsets needs O(n · 2ⁿ) output no matter how clever the algorithm is.
| Code | Time | Auxiliary space | Why |
|---|---|---|---|
| Iterative sum of an array | O(n) | O(1) | One accumulator |
| Recursive sum of an array | O(n) | O(n) | n frames on the call stack |
| Recursive binary search | O(log n) | O(log n) | Depth log₂ n (O(1) if written iteratively) |
| Merge sort | O(n log n) | O(n) | Merge buffer plus O(log n) stack |
| Quick sort | O(n log n) average | O(log n) average, O(n) worst | Recursion depth; recurse on the smaller side first to guarantee O(log n) |
| DFS on a graph | O(V + E) | O(V) | Visited set plus stack depth up to V |
| Memoized Fibonacci | O(n) | O(n) | Memo table and stack depth both n |
From constraints to target complexity
Problem constraints are a strong hint about the intended solution. With a budget of roughly 10⁸ simple operations per second, the maximum input size tells you which complexity to aim for, and the complexity tells you which family of techniques to consider.
| Maximum n | Target complexity | Typical techniques |
|---|---|---|
| n ≤ 10 to 12 | O(n!) or O(n · n!) | All permutations, brute force |
| n ≤ 20 to 25 | O(2ⁿ · n) | Bitmask enumeration, Backtracking, bitmask DP |
| n ≤ 40 | O(2^(n/2) · n) | Meet in the middle |
| n ≤ 100 to 500 | O(n³) | Floyd-Warshall, interval DP, triple loops |
| n ≤ 2,000 to 5,000 | O(n²) | 2D DP (LCS & Edit Distance), all pairs |
| n ≤ 10⁵ to 10⁶ | O(n log n) or O(n) | Sorting, heaps, Binary Search, Two Pointers, Segment Trees |
| n ≤ 10⁷ to 10⁸ | O(n), small constant | Linear scans, sieves, Prefix Sums & Difference Arrays |
| n ≤ 10¹² | O(√n) | Trial division, divisor enumeration |
| n ≤ 10¹⁸ | O(log n) or O(1) | Fast exponentiation, binary search on the answer, closed-form math |
An analysis checklist
- 1
Name the variables
n for the array length, m for a second input, L for string length, V and E for graphs. Never merge independent sizes.
- 2
Find the hot spot
Locate the statement that runs the most and count its executions as a sum over the loop variables.
- 3
Look inside library calls
sortedis O(n log n),list.insert(0, x)is O(n), slicing copies, string concatenation in a loop can be O(n²). - 4
Write recurrences for recursion
Solve them with a recursion tree, the Master Theorem, or substitution.
- 5
Amortize where it is honest
If a pointer only moves forward or a structure doubles, bound the whole run instead of each iteration.
- 6
Account for memory
Include auxiliary structures and the maximum recursion depth.
Complexity
| Code shape | Count or recurrence | Time | Space |
|---|---|---|---|
| Single loop | n | O(n) | O(1) |
| Nested loops over the same input | n² or n(n − 1)/2 | O(n²) | O(1) |
| Halving or doubling loop | log₂ n | O(log n) | O(1) |
| Harmonic loop (step by i) | n · Hₙ | O(n log n) | O(1) |
| Recursive binary search | T(n) = T(n/2) + 1 | O(log n) | O(log n) |
| Merge sort | T(n) = 2T(n/2) + n | O(n log n) | O(n) |
| Naive Fibonacci | T(n) = T(n − 1) + T(n − 2) + 1 | O(2ⁿ) | O(n) |
| Dynamic array append | Amortized, doubling | O(1) | O(n) |
Naive Fibonacci is more tightly Θ(φⁿ) with φ ≈ 1.618; O(2ⁿ) is the common upper bound.
Implementation
A doubling array that counts every element write, including copies during resizes. The writes-per-append ratio stays below 3, which is the aggregate argument for amortized O(1) appends made concrete.
class DynamicArray:
"""Doubling array that counts element writes to show amortized O(1) appends."""
def __init__(self) -> None:
self.capacity = 0
self.size = 0
self.data: list[int] = []
self.writes = 0 # element writes, including copies
def append(self, value: int) -> None:
if self.size == self.capacity:
new_capacity = max(1, 2 * self.capacity)
new_data = [0] * new_capacity
for i in range(self.size): # copy: O(size)
new_data[i] = self.data[i]
self.writes += 1
self.data, self.capacity = new_data, new_capacity
self.data[self.size] = value # the append itself: O(1)
self.size += 1
self.writes += 1
arr = DynamicArray()
for n in range(1, 1_000_001):
arr.append(n)
if n in (10, 1_000, 1_000_000):
print(f"n={n:>9} writes={arr.writes:>9} writes/n={arr.writes / n:.2f}")
# Prints ratios 2.50, 2.02, 2.05: always below 3Key takeaways
- Count how often the innermost statement runs as a sum over loop variables; nesting depth alone can mislead (halving loops and forward-only pointers are linear).
- Recursive code becomes a recurrence
T(n) = a · T(n/b) + f(n); recursion trees show whether the root, every level or the leaves dominate. - The Master Theorem compares f(n) with n^(log_b a): smaller gives Θ(n^(log_b a)), equal (up to logᵏ) adds a log factor, larger gives Θ(f(n)).
- Amortized analysis bounds the worst-case total over a sequence: doubling arrays give O(1) amortized appends by the aggregate, accounting or potential method.
- Space includes auxiliary structures and the call stack: recursion depth, not the number of calls.
- Input constraints map to target complexities: n ≤ 20 suggests O(2ⁿ), n ≤ 10⁵ suggests O(n log n).
Common pitfalls
- Multiplying loop depths without checking whether inner bounds depend on outer variables or shrink geometrically.
- Applying the Master Theorem to
T(n) = T(n − 1) + nor to uneven splits, where it does not apply. - Proving
T(n) ≤ cn + nand calling it O(n): induction must reproduce the exact hypothesis. - Confusing amortized O(1) with "every operation is O(1)"; individual operations can still be O(n).
- Forgetting the call stack when claiming O(1) space for a recursive solution.
Interview tips
- For recursive solutions, say the recurrence out loud, then its solution: "T(n) = 2T(n/2) + O(n), so O(n log n)."
- When a while loop sits inside a for loop, explain why the total is linear if a pointer only moves forward. Interviewers listen for that argument.
- Mention amortization explicitly for dynamic arrays, hash table resizing and queue-from-two-stacks; it shows depth.
- Quote space including recursion depth, and offer an iterative version if depth could reach 10⁵ or more.
Real-world applications
- Choosing growth factors for dynamic arrays and hash tables in standard libraries.
- Predicting the cost of divide-and-conquer algorithms (FFT, Karatsuba, Strassen) before implementing them.
- Estimating recursion depth to avoid stack overflows in production code.
- Reading constraints in coding contests and interviews to pick the right technique.
Practice problems
Test yourself
What is the time complexity of: i = n; while i > 0: (do i units of work); i //= 2?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.