Algorithmic Complexity (DSA #1)
Two programs solve the same problem. On your laptop both finish instantly, so they look equivalent. You ship one to production, it meets ten users, then a thousand, then a hundred thousand — and one of them melts a server while the other barely notices. The difference is not the language or the machine; it is how the work grows with the input. That growth rate is what algorithmic complexity measures.
This chapter is the lens for the whole course. Every data structure and algorithm that follows will be judged by the same question: as \(n\) grows, what happens to the time and the memory? Get comfortable with the notation now and every later chapter reads faster.
Time vs space complexity
Complexity describes resource use as a function of input size \(n\):
- Time complexity — how many elementary operations the algorithm performs.
- Space complexity — how much extra memory it allocates, ignoring the input itself.
We ignore constant factors and machine speed because we care about the shape of growth. An algorithm doing \(5n\) operations and one doing \(n\) operations both scale linearly; the constant 5 matters for a benchmark, not for which one wins at scale. We also ignore lower-order terms: \(3n^2 + 40n + 900\) is, for large \(n\), simply \(n^2\).
\[ T(n) = 3n^2 + 40n + 900 \;\longrightarrow\; O(n^2) \]
The reason to care is concrete. At \(n = 10^6\): an \(O(n)\) algorithm does a million steps, an \(O(n^2)\) algorithm a trillion, and an \(O(n \log n)\) algorithm about twenty million. Memory matters similarly — an \(O(n)\) table that is fine at 1,000 rows is a crash at 100 million.
Asymptotic notation: O, Ω, θ
Three notations bound a function from different sides:
- Big-O (\(O\)) — an upper bound: the growth is at most this (ignoring constants). “\(O(n^2)\)” means no worse than quadratic.
- Big-Ω (\(\Omega\)) — a lower bound: at least this.
- Big-θ (\(\Theta\)) — a tight bound: both an upper and a lower bound, so the growth is exactly this class.
\[ f(n) = \Theta(g(n)) \iff f(n) = O(g(n)) \ \text{and}\ f(n) = \Omega(g(n)) \]
In interviews and engineering, people say “O” when they mean θ (the tight bound). A single algorithm can be \(\Omega(n)\) (it must at least read the input) and \(O(n^2)\) (a naive implementation); the truth is somewhere between, and a good implementation tightens it.
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[->, black!45] (0,0) -- (7.4,0) node[below, font=\small] {$n$};
\draw[->, black!45] (0,0) -- (0,3.3) node[left, font=\small] {work};
\draw[thick, green!55!black] (0,0.2) -- (7.2,0.6) node[right, font=\small] {$O(1)$};
\draw[thick, blue!70!black] (0,0.2) .. controls (2,1.0) and (4.5,1.6) .. (7.2,1.9) node[right, font=\small] {$O(\log n)$};
\draw[thick, orange!80!black] (0,0.2) -- (6.6,2.4) node[right, font=\small] {$O(n)$};
\draw[thick, red!70!black] (0,0.2) .. controls (3,0.8) and (5,1.8) .. (6.4,3.1) node[right, font=\small] {$O(n^2)$};
\end{tikzpicture}
The runtimes you will meet
| Class | Name | Example |
|---|---|---|
| \(O(1)\) | constant | array index, hash lookup (average) |
| \(O(\log n)\) | logarithmic | binary search, balanced-tree lookup |
| \(O(n)\) | linear | scan an array, single pass |
| \(O(n \log n)\) | linearithmic | merge sort, heap sort, good sorting bounds |
| \(O(n^2)\) | quadratic | nested loops, bubble sort |
| \(O(2^n)\) | exponential | subsets, naive recursion |
| \(O(n!)\) | factorial | permutations |
The jump from \(O(n \log n)\) to \(O(n^2)\) is the most important boundary in practice: it is the difference between a sort and a nested scan. Most algorithmic improvements in this course are about pushing an \(O(n^2)\) solution down to \(O(n \log n)\) or \(O(n)\).
How to calculate complexity
There is a reliable recipe.
Sequential code adds. Two loops one after another are \(O(n) + O(m)\), which is \(O(n + m)\).
def two_passes(a):
total = 0
for x in a: # O(n)
total += x
for x in a: # O(n)
total -= x
return total # total: O(n) + O(n) = O(n)
Nested loops multiply. A loop over \(n\) containing a loop over \(m\) is \(O(n \cdot m)\).
def all_pairs(a, b):
for x in a: # n iterations
for y in b: # m iterations each
print(x, y) # total: O(n * m)
Halving the input gives a logarithm. Each halving step turns \(n\) into \(n/2\); it takes \(\log_2 n\) steps to reach 1. So \(n = 1024\) takes about 10 steps, and \(n = 10^6\) about 20.
def halve(n):
steps = 0
while n > 1:
n //= 2 # n, n/2, n/4, ... -> O(log n)
steps += 1
return steps
print(halve(1_000_000)) # ~20
Recursion needs a recurrence. Count the work per call and how many calls happen. This naive Fibonacci calls itself twice per level, giving \(O(2^n)\):
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2) # two branches -> O(2^n)
Memoizing the result — storing each answer once — collapses the tree to \(O(n)\) (Chapter 26). Seeing the exponential recurrence is the first step to fixing it.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.5cm, inner sep=0pt, font=\scriptsize}]
\node[n, fill=orange!25] (r) at (0,0) {5};
\node[n] (a) at (-1.6,-0.9) {4}; \node[n] (b) at (1.6,-0.9) {3};
\node[n] (c) at (-2.4,-1.8) {3}; \node[n] (d) at (-0.8,-1.8) {2};
\node[n] (e) at (0.8,-1.8) {2}; \node[n] (f) at (2.4,-1.8) {1};
\draw[->, thick] (r) -- (a); \draw[->, thick] (r) -- (b);
\draw[->, thick] (a) -- (c); \draw[->, thick] (a) -- (d);
\draw[->, thick] (b) -- (e); \draw[->, thick] (b) -- (f);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.3) {every call branches twice: $O(2^n)$ and repeated work};
\end{tikzpicture}
Amortized complexity
Some operations are occasionally expensive but cheap on average. A dynamic array that doubles its capacity is the classic case: appending is usually \(O(1)\), but every so often it copies all \(n\) elements, which is \(O(n)\). Spread across the growth, each append costs amortized \(O(1)\).
\[ \frac{1 + 2 + 4 + \dots + n}{n} < \frac{2n}{n} = 2 = O(1) \text{ amortized} \]
Amortized complexity is why list.append in Python feels constant even though resizing is linear. It is a statement about a sequence of operations, not any single one.
Space complexity
Space complexity is often the constraint that bites first. Three notes:
- Auxiliary space excludes the input; when people say “\(O(1)\) space” they mean no memory proportional to \(n\) beyond the input.
- Recursion uses the call stack. A recursive DFS on a path of length \(n\) uses \(O(n)\) stack space even though its explicit memory is constant.
- Trading space for time is the central move in algorithms: a hash map turns an \(O(n)\) lookup into \(O(1)\) at the cost of \(O(n)\) memory (Chapter 6).
def has_duplicates_brute(a): # O(n^2) time, O(1) space
for i in range(len(a)):
for j in range(i + 1, len(a)):
if a[i] == a[j]:
return True
return False
def has_duplicates_fast(a): # O(n) time, O(n) space
seen = set()
for x in a:
if x in seen:
return True
seen.add(x)
return False
Same answer, opposite resource profiles. Choosing between them is algorithm design.
Pitfalls
- Dropping constants too early. \(O(n)\) with a constant of 1000 can lose to \(O(n \log n)\) for realistic \(n\). Complexity predicts growth, not a benchmark.
- Forgetting the hidden loop. A call inside a loop that is itself \(O(n)\) (a list membership test, a string concatenation) turns an \(O(n)\) loop into \(O(n^2)\).
- Ignoring the recursion stack. Recursive solutions are not \(O(1)\) space; the call stack counts.
- Confusing amortized with worst-case. A single append can be \(O(n)\); the sequence is amortized \(O(1)\).
- Assuming hash operations are always \(O(1)\). They are \(O(1)\) on average; adversarial or colliding keys degrade to \(O(n)\) (Chapter 6).
Why does halving the input produce \(O(\log n)\)? What are the time and space complexity of recursive DFS on a graph with \(n\) nodes?
ASolution
Each halving step reduces the problem size by half, so it takes about \(\log_2 n\) steps to go from \(n\) to 1. Recursive DFS visits each node once (\(O(n)\) time) but the call stack can hold up to \(n\) frames on a path, so auxiliary space is \(O(n)\).
Next: Arrays (DSA #2) — the contiguous block of memory everything else is compared against.