Skip to content

Complexity Analysis

## Why Complexity Analysis Matters

A system that handles 1,000 requests per second at USD 10,000 per month in compute costs is Fundamentally different from one that handles 10 requests per second at the same cost. The Difference is almost always algorithmic: the data structure, the traversal strategy, the caching Policy. Before you optimise constants, before you add hardware, before you profile — understand the Asymptotic behaviour of your algorithm.

Complexity analysis gives you a language for reasoning about how an algorithm scales. It abstracts Away machine-specific details (clock speed, cache size, instruction set) and lets you compare Algorithms on their mathematical properties. This is not academic; it is the difference between a Query that completes in 10 milliseconds and one that takes 10 minutes when the dataset grows from 10,000 to 10,000,000 rows.

O(g(n))O(g(n)) is the set of all functions f(n)f(n) for which there exist positive constants cc and n0n_0 Such that:

0 \le f(n) \le c \cdot g(n) \quad \mathrm{for all n \ge n_0

Big-O provides an upper bound on the growth rate of a function. Saying f(n)=O(n2)f(n) = O(n^2) means That f(n)f(n) grows no faster than n2n^2 (up to a constant factor), for sufficiently large nn.

## Example: nested loop is O(n^2)
def print_all_pairs(arr):
for i in range(len(arr)): # O(n)
for j in range(len(arr)): # O(n)
print(arr[i], arr[j]) # O(1)
## Total: O(n) * O(n) * O(1) = O(n^2)

Ω(g(n))\Omega(g(n)) is the set of all functions f(n)f(n) for which there exist positive constants cc and n0n_0 such that:

0 \le c \cdot g(n) \le f(n) \quad \mathrm{for all n \ge n_0

Big-Omega provides a lower bound. If an algorithm is Ω(nlogn)\Omega(n \log n)It means no matter how Clever your implementation, the algorithm will take at least cnlognc \cdot n \log n steps for large nn.

Θ(g(n))\Theta(g(n)) is the intersection: f(n)Θ(g(n))f(n) \in \Theta(g(n)) if and only if f(n)O(g(n))f(n) \in O(g(n)) and f(n)Ω(g(n))f(n) \in \Omega(g(n)). This is the tight bound — the function grows at exactly the same rate As g(n)g(n)Up to constant factors.

0 \le c_1 \cdot g(n) \le f(n) \le c_2 \cdot g(n) \quad \mathrm{for all n \ge n_0