Sub topic 1
Complexity and recurrences: the toolkit for comparing algorithms
Prerequisites
This chapter assumes you can:
- Read Big-O, Theta, and Omega notation.
- Follow a simple recursive function.
- Read short Python.
Later chapters rely on the results here. The recurrences below recur throughout greedy, dynamic programming, and graph algorithms.
Why compare algorithms by growth rate
Two correct algorithms can differ by a factor of millions on large inputs. Running time depends on the machine, so we count basic operations as a function of the input size n and keep only the dominant term. For GATE, you will mostly need to place an algorithm in one of the classes below.
| Class | Typical source in this tutorial |
|---|---|
| O(1) | Array index, union-find with path compression (amortized, near constant) |
| O(log n) | Binary heap push or pop, binary search |
| O(n) | One scan of an array, BFS/DFS on a tree |
| O(n log n) | Sorting by finish time or edge weight, Huffman with a heap |
| O(n^2) | Simple nested loops, LCS on two strings of length n |
| O(n^3) | Floyd-Warshall, matrix chain table |
| O(2^n) | Trying every subset, naive recursion on overlapping subproblems |
Three habits prevent most mistakes:
- State the input size explicitly (n items, V vertices, E edges, capacity W).
- Separate worst case from average and amortized cost.
- Count the dominant step. In Kruskal's algorithm, the sort of E edges costs O(E log E), which swamps the near-constant union-find calls.
Counting loops
Single loops give O(n). Nested loops multiply when the inner bound does not depend on the outer variable. When it does, you must sum.
def count_pairs(n):
steps = 0
for i in range(n):
for j in range(i):
steps += 1
return steps
print(count_pairs(10)) # 45The inner loop runs 0 + 1 + ... + (n-1) = n(n-1)/2 times, which is Θ(n^2). Halving the constant does not change the class.
A loop whose variable doubles (i *= 2) runs about log2 n times. A loop over a graph's adjacency lists touches each edge a constant number of times, so it costs O(V + E), not O(V * E).
Recurrences
A recursive algorithm's cost is described by a recurrence: a formula for T(n) in terms of T on smaller inputs. You need a base case and a recursive case, just as in the code.
Three methods solve most exam recurrences:
- Substitution. Guess a bound and prove it by induction.
- Recursion tree. Draw the calls level by level, sum the work per level, then sum the levels.
- Master theorem. Apply a formula to recurrences of the form T(n) = aT(n/b) + f(n), with a ≥ 1 and b > 1.
Let c = log_b a, which measures how fast the number of subproblems grows. Compare f(n) with n^c:
| Case | Condition | Result |
|---|---|---|
| 1 | f(n) grows polynomially slower than n^c | Θ(n^c) |
| 2 | f(n) = Θ(n^c) | Θ(n^c log n) |
| 3 | f(n) grows polynomially faster than n^c, and a·f(n/b) ≤ k·f(n) for some k < 1 | Θ(f(n)) |
Worked examples:
- T(n) = 2T(n/2) + n. Here c = 1 and f(n) = n, so case 2 gives Θ(n log n). This is merge sort.
- T(n) = T(n/2) + 1. Here c = 0 and f(n) = 1 = Θ(n^0), so case 2 gives Θ(log n). This is binary search.
- T(n) = 4T(n/2) + n. Here c = 2, which beats f(n) = n, so case 1 gives Θ(n^2).
Not every recurrence fits. T(n) = T(n-1) + n shrinks by subtraction, not division. Unrolling it gives n + (n-1) + ... + 1, which is Θ(n^2). T(n) = 2T(n/2) + n log n falls in a gap between cases 2 and 3 of the basic theorem, so use a recursion tree: each of the log n levels costs about n log n, which gives Θ(n log^2 n).
Why overlapping subproblems matter
Dynamic programming exists because of one recurrence shape. Naive Fibonacci satisfies T(n) = T(n-1) + T(n-2) + 1, which grows exponentially, because the same subproblems are solved again and again. Counting distinct subproblems instead gives a linear bound.
from functools import lru_cache
calls = 0
def fib_naive(n):
global calls
calls += 1
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_naive(20), calls) # 6765 21891
print(fib_memo(20), fib_memo.cache_info().misses) # 6765 21The naive version makes 21891 calls. The memoized version computes only 21 distinct values, one for each n from 0 to 20. A useful rule: the cost of a DP is (number of distinct subproblems) × (work per subproblem).
Common errors
- Applying the Master theorem to T(n) = T(n-1) + T(n-2), or when a < 1, or when the subproblems have unequal sizes.
- Comparing f(n) with n^c by constant factors. Cases 1 and 3 need a polynomial gap, so n log n versus n is not case 3.
- Treating 0/1 knapsack's O(nW) as polynomial in the input size. W is a number, and its input length is only log W bits, so the bound is pseudo-polynomial.
- Forgetting that a dense graph has E up to V^2, so O(E log V) can become O(V^2 log V).
Exercise
Solve T(n) = 3T(n/2) + n with the Master theorem, and say whether the result is faster than n^2.
Show answer
Here a = 3 and b = 2, so c = log2 3 ≈ 1.585. Since f(n) = n grows polynomially slower than n^1.585, case 1 applies and T(n) = Θ(n^(log2 3)). This is about n^1.585, which is asymptotically smaller than n^2.
Exercise
A 0/1 knapsack algorithm runs in O(nW). Why is it not a polynomial-time algorithm in the input size, and how does the memoized Fibonacci above avoid the exponential blowup?
Show answer
W is given in binary, so its encoding takes about log2 W bits. If W doubles, the input grows by one bit but the running time doubles, so the time is exponential in the input length (pseudo-polynomial). Memoized Fibonacci avoids the blowup because it solves each of the n + 1 distinct subproblems once, giving O(n) calls instead of exponentially many.