Time & Space Complexity — counting what really grows
Big-O, Ω and Θ from their formal definitions; analysing loops, recursion and divide-and-conquer; amortized costs; the real cost of Python's built-ins — with worked examples, proofs and seven working labs.
AChapter introduction
Prerequisites
You should be comfortable writing Python functions, loops and recursion, and using lists and dictionaries. On the maths side you need powers and logarithms (log₂ 1024 = 10) and the idea of a function's graph. No calculus is required; one optional shortcut uses limits.
Learning objectives
After completing this chapter you will be able to:
- Define time complexity and space complexity precisely, and explain why we count operations rather than seconds.
- Read, use and prove statements in O, Ω and Θ notation with explicit constants c and n₀.
- Derive the complexity of single, nested, triangular and halving loops, of recursion, and of divide-and-conquer recurrences (including the Master Theorem).
- Distinguish best, average, worst and amortized cost — and input space from auxiliary space and call-stack space.
- Predict the cost of everyday Python operations on
list,dict,setanddeque, and verify predictions with operation counts, timing and memory tracing. - Use complexity to choose between solutions in interviews and production systems, and know when Big-O alone is not enough.
BFundamental understanding
What is complexity?
An algorithm consumes two scarce resources: time (how many steps the processor performs) and space (how much memory it occupies while running). Complexity analysis describes how those resource needs grow as a function of the input size n. MIT's 6.006 frames efficiency the same way: running time is measured by counting fixed-time operations, so the answer does not depend on a particular machine [2], and asymptotic ("big-O") notation describes the growth of the runtime without worrying about computers, compilers or implementations [3].
Why the concept exists
Timing a program with a stopwatch tells you about that program on that machine with that input. Princeton's Sedgewick and Wayne list the reasons we analyse algorithms instead: to predict performance, compare algorithms, provide guarantees and understand the theory — with the primary practical reason being to avoid performance bugs [6]. Their N-body example makes the point: a brute-force simulation needs about n² steps, which limited what scientists could simulate until faster algorithms arrived [6].
A short, verifiable history
The symbol O predates computers. Donald Knuth traced it to Paul Bachmann's 1894 number-theory book, after which Edmund Landau popularised it (and introduced little-o) [13]. In 1976 Knuth argued in SIGACT News that computer scientists also need notation for lower bounds and tight bounds, and proposed the now-standard Ω and Θ definitions [13]. Today these definitions are the ones taught in CLRS and in university courses [1][4].
Fundamental principles (introduced one term at a time)
| Term | Meaning |
|---|---|
| Input size n | The quantity that grows: number of list elements, characters, vertices + edges, bits of a number… |
| Primitive operation | A step that costs O(1) in the model: integer and logical arithmetic, comparisons, bitwise operations, reading or writing one machine word [2]. |
| Word-RAM model | A machine whose words are w bits, with w ≥ log₂ n so that every memory address fits in one word [2]. |
| Order of growth | The dominant term of T(n) with constants dropped: e.g. T(n) ∼ c·f(n), where f(n) is typically log n, n, n log n, n², n³ [5]. |
| Asymptotic | Concerned with behaviour "for all sufficiently large n"; small inputs are ignored [4]. |
| Worst / best / average case | The maximum, minimum, or expected cost over all inputs of size n [1][4]. |
| Amortized cost | Total cost of a sequence of k operations divided by k [7]. |
| Auxiliary space | Extra memory the algorithm allocates beyond the input itself (variables, copies, call stack). |
CThe problem complexity analysis solves
Problem description
Input: two or more correct algorithms for the same task, plus an expected range of input sizes. Output: a prediction of how each will scale — and therefore which one to ship. Constraints: the prediction must be independent of hardware, language and compiler, and must hold as n grows beyond what we can test.
Why the naive approach (benchmarking only) falls short
Measuring wall-clock time is valuable — Princeton teaches an empirical "doubling" method in which you time the program at n and 2n and inspect the ratio [5] — but timing alone cannot tell you why a program is slow, cannot be done before the code exists, and cannot safely be extrapolated from small tests to 1000× larger production inputs. Wall-clock numbers also mix in effects of the machine, the interpreter and the cache that asymptotic analysis deliberately abstracts away [3].
How complexity analysis improves the situation
By counting the dominant operations as a function of n, we obtain a machine-independent "law" such as T(n) ∼ n³/6. Princeton shows this for the brute-force 3-SUM program, whose inner if executes exactly n(n−1)(n−2)/6 times, i.e. ∼ n³/6 [5]. A cubic law immediately predicts that doubling n multiplies running time by about 2³ = 8 — which is exactly what their measurements show [5].
DVisual whiteboard explanations
Before any formulas, let's draw the ideas the way a professor would on a whiteboard. Colours keep the same meaning throughout the chapter.
EInteractive lab
These visualisers run entirely in your browser. Every button does real work: values are computed live, not pre-recorded. More visualisers appear in later sections where they fit the explanation (call stack in F, the formal definition in G, amortized arrays in H, and a self-check quiz in M).
FInternal working: how cost is actually counted
The machine model underneath
To count "steps", we need to agree on what one step is. Courses such as MIT 6.006 use the word-RAM: memory is an array of w-bit words, and integer arithmetic, logical and bitwise operations, comparisons, and reading or writing a word at a given address each take O(1) time [2]. Because w ≥ log₂ n, an index into an array of n items fits in one word, which is exactly why a[i] is a constant-time operation [2].
The counting procedure
- Choose the input size n. For a list it is its length; for a graph, usually V and E; for a number, its number of bits.
- Choose the basic operation — the one in the innermost loop. Princeton's method focuses on the most frequently executed instructions, since time outside the inner loop is relatively insignificant [5].
- Write the count as a sum (loops) or a recurrence (recursion).
- Simplify to a closed form, e.g. ∑ᵢ₌₀ⁿ⁻¹ (n−1−i) = n(n−1)/2.
- Keep the leading term, drop its constant: n(n−1)/2 ∼ n²/2 ⟹ Θ(n²) [5][1].
Worked example: line-by-line cost of find_max
This is the CLRS-style "cost × times" table [1]. Let cₖ be the constant cost of line k.
def find_max(a): # n = len(a) ≥ 1
best = a[0] # line 1
for x in a[1:]: # line 2
if x > best: # line 3
best = x # line 4
return best # line 5
| Line | Cost | Times executed | Comment |
|---|---|---|---|
| 1 | c₁ | 1 | one read, one write |
| 2 | c₂ | n (n−1 iterations + loop exit); slicing a[1:] also copies n−1 references | Python slice is O(j−i) [9] |
| 3 | c₃ | n − 1 | one comparison per remaining element |
| 4 | c₄ | between 0 (best) and n − 1 (worst: increasing input) | data-dependent |
| 5 | c₅ | 1 |
Summing gives T(n) = A·n + B for constants A, B in every case, so T(n) = Θ(n). Note the hidden detail: the slice a[1:] allocates a new list of n−1 references, making the auxiliary space Θ(n) instead of Θ(1). Iterating with range(1, len(a)) avoids that copy.
Memory representation: where does space go?
A running program's memory splits into the input (given to us), auxiliary data (variables, new lists, hash tables we build), and the call stack (one frame per active function call). Space complexity usually means the auxiliary part plus the stack. In CPython a list is internally an array of references to objects [10], and the interpreter limits recursion depth with a configurable limit that exists to prevent infinite recursion from overflowing the C stack and crashing Python [11].
sum_recursive(a, 0) until (a, 1) returns, and so on, so n + 1 purple frames are alive at the deepest point: O(n). Technical interpretation: recursion depth is space. With CPython's default limit of 1,000 frames (see sys.getrecursionlimit() [11]), sum_recursive on 100,000 items raises RecursionError, which we demonstrate in Section I.Notice what the lab shows: the naive tree has exponentially many nodes (the number of calls for fib(n) is 2·F(n+1) − 1, e.g. 177 calls for n = 10 in our Python run), yet the stack never gets deeper than about n frames, because only one root-to-leaf path is alive at a time. Memoization collapses time to linear (2n − 1 calls) while space stays linear. Time and space are different budgets, and recursion spends them differently.
Edge cases that change the answer
- Empty input (n = 0). Most loops run zero times, but a function like
find_max([])must decide whether to raise an error — complexity doesn't excuse incorrect behaviour. - Early exit. Linear search that finds the target at index 0 costs 1 comparison (best case), but its worst case is still n.
- Hidden copies. Slicing,
list(x),sorted(x), string building anda + ball allocate new storage proportional to their output [9]. - Input size in bits. For numeric inputs, the size is the number of digits, not the value (see Section N).
GMathematical foundation
The three core definitions
Let f, g be functions from non-negative integers to non-negative reals. The definitions below are those of CLRS and Stanford CS161 [1][4]:
MIT's Mathematics for Computer Science text stresses that Big-O gives an upper bound on growth and is the most frequently used asymptotic notation [14]. The "=" sign is a long-standing abuse of notation: O(g) is really a set of functions, and MIT's 6.006 recitation notes call f(x) = Θ(x²) "really misleading" for that reason [3].
Worked proofs
Claim 1. 3n² + 5n + 2 = O(n²). Proof. For n ≥ 1 we have 5n ≤ 5n² and 2 ≤ 2n², so 3n² + 5n + 2 ≤ 10n². Choose c = 10, n₀ = 1. ∎ (Many witnesses work: c = 4 with n₀ = 6 also works, because n² − 5n − 2 ≥ 0 once n ≥ 5.37.)
Claim 2. 3n² + 5n + 2 = Ω(n²). Proof. For n ≥ 0, 3n² + 5n + 2 ≥ 3n². Choose c = 3, n₀ = 0. ∎ Together, Claims 1 and 2 give Θ(n²).
Claim 3. n² ≠ O(n). Proof by contradiction. Suppose n² ≤ c·n for all n ≥ n₀. Dividing by n gives n ≤ c for all n ≥ n₀, which fails at n = max(n₀, ⌈c⌉ + 1). ∎
Rules that make analysis fast
| Rule | Statement | Example |
|---|---|---|
| Constant factors | O(k·f) = O(f) for any constant k > 0 | 7n = O(n) |
| Sum rule | O(f) + O(g) = O(max(f, g)) | sorting then scanning: n log n + n = O(n log n) |
| Product rule | O(f)·O(g) = O(f·g) | a loop of n iterations each doing O(log n) work: O(n log n) |
| Transitivity | f = O(g) and g = O(h) ⟹ f = O(h) | log n = O(n), n = O(n²) ⟹ log n = O(n²) |
| Log bases | loga n = logb n / logb a, a constant factor apart | O(log₂ n) = O(log₁₀ n) = O(log n) |
| Hierarchy | 1 ≺ log n ≺ √n ≺ n ≺ n log n ≺ n² ≺ n³ ≺ 2ⁿ ≺ n! | any polynomial is o(2ⁿ); any power of log n is o(nε) |
These follow directly from the definitions and are developed in CLRS Chapter 3 and MIT's asymptotics notes [1][14].
Summations for loops
The arithmetic series explains triangular loops (Figure D.4 ③). The geometric series explains why doubling a dynamic array costs O(n) in total (Section H) [7]. The harmonic series appears when the inner loop runs n/i times (e.g. sieve-like loops) [1].
Recurrences for recursion
| Recurrence | Typical algorithm | Solution |
|---|---|---|
| T(n) = T(n/2) + O(1) | binary search | Θ(log n) |
| T(n) = T(n−1) + O(1) | recursive sum / factorial | Θ(n) |
| T(n) = 2T(n/2) + Θ(n) | merge sort | Θ(n log n) [4] |
| T(n) = T(n−1) + Θ(n) | selection / insertion sort (worst) | Θ(n²) |
| T(n) = 2T(n−1) + O(1) | Towers of Hanoi, all subsets | Θ(2ⁿ) |
| T(n) = T(n−1) + T(n−2) + O(1) | naive Fibonacci | Θ(φⁿ), φ ≈ 1.618 |
The Master Theorem
For divide-and-conquer recurrences T(n) = a·T(n/b) + f(n) with a ≥ 1, b > 1, compare f(n) with the "watershed" nlogb a, the total cost of the leaves of the recursion tree [8][1]:
| Case | Condition | Result | Example |
|---|---|---|---|
| 1 · leaves dominate | f(n) = O(nlogba − ε) for some ε > 0 | Θ(nlogba) | T(n) = 8T(n/2) + n² ⟹ Θ(n³) |
| 2 · balanced | f(n) = Θ(nlogba logk n), k ≥ 0 | Θ(nlogba logk+1 n) | merge sort: a = b = 2, f = n ⟹ Θ(n log n) |
| 3 · root dominates | f(n) = Ω(nlogba + ε) and a·f(n/b) ≤ k·f(n) for some k < 1 | Θ(f(n)) | T(n) = 2T(n/2) + n² ⟹ Θ(n²) |
HOperations and complexity analysis
Best, average, worst — and why worst case is the default
Stanford CS161 frames worst-case analysis as a game against an adversary who picks the input: a worst-case guarantee holds for every input of size n, which makes it a strong and robust promise [4]. Average-case analysis needs an assumed input distribution (e.g. "every permutation equally likely") [1]. Best case is rarely useful on its own, since almost any algorithm can be made fast on some lucky input.
Master table of classic operations
Assumptions: n = number of elements; arrays are random-access; "sorted" is stated where needed; hash tables assume a good hash function.
| Operation | Best | Average | Worst | Auxiliary space |
|---|---|---|---|---|
Access a[i] (array / Python list) | Θ(1) | Θ(1) | Θ(1) | Θ(1) |
| Linear search (unsorted) | Θ(1) | Θ(n) | Θ(n) | Θ(1) |
| Binary search (sorted) | Θ(1) | Θ(log n) | Θ(log n) | Θ(1) iterative · Θ(log n) recursive |
| Find max / sum | Θ(n) | Θ(n) | Θ(n) | Θ(1) |
| Insertion sort | Θ(n) (sorted input) | Θ(n²) | Θ(n²) | Θ(1) |
| Merge sort | Θ(n log n) | Θ(n log n) | Θ(n log n) | Θ(n) |
Python list.sort() / sorted() | O(n) on already-sorted or reverse-sorted input | O(n log n) | O(n log n) [9] | O(n) |
Hash lookup / insert (dict, set) | O(1) | O(1) | O(n) if all keys collide [9] | O(1) per op |
Dynamic array append (list.append) | O(1) | O(1) amortized | O(n) for one resize [9] | O(n) during resize |
| Brute-force duplicate check (all pairs) | Θ(1) (dup at front) | — | Θ(n²) | Θ(1) |
| Naive recursive Fibonacci | Θ(φⁿ) calls on every input n | Θ(n) stack | ||
Reasoning: binary search halves the interval each comparison (Θ(log n)); insertion sort's inner loop shifts 0 elements on sorted input and up to i elements on reverse-sorted input, giving ∑i = Θ(n²) [1]; merge sort is covered by Figure G.2 [4]; Python's sort is adaptive, so sorted or reverse-sorted input needs only O(n) comparisons [9].
Theory vs. actual Python behaviour
The CPython documentation publishes complexities for built-in types. These are the entries you will use most [9][10]:
| Type | Operation | Cost | Note |
|---|---|---|---|
list | l[k], l[k] = x, len(l) | O(1) | array of references [10] |
l.append(x) | O(1) amortized | occasional O(n) resize [9] | |
l.pop() (last) vs l.pop(k) | O(1) vs O(n − k) | pop(0) shifts every element | |
l.insert(k, x), del l[k] | O(n − k) | elements after k move | |
x in l, min(l), max(l) | O(n) | linear scan | |
l[i:j] | O(j − i) | creates a copy | |
l.sort() | O(n log n) | O(n) if already ordered | |
dict / set | k in d, d[k], d[k] = v, del d[k], s.add | O(1) average | O(n) worst case when every key hashes to the same value [9] |
s1 & s2 | O(min(len(s1), len(s2))) | iterates the smaller set | |
collections.deque | append, appendleft, pop, popleft | O(1) | use instead of list.pop(0) for queues [12] |
sum() or sorted() run their loops in C, so two Θ(n) solutions can differ by a large constant factor. MIT's 6.042 notes warn that constants hidden by O can matter in practice [14], and the Python wiki notes other implementations may differ from CPython [10]. Use complexity to choose the class; use measurement to choose between solutions in the same class.Amortized analysis: why append is O(1) although resizing is O(n)
Amortized cost = total cost of a sequence of k operations ÷ k [7]. It is a worst-case guarantee about sequences, not an average over random inputs. MIT 6.046 presents three techniques — the aggregate, accounting and potential methods — and applies them to table doubling [7][18].
Aggregate method. Start with capacity 1 and double when full. Inserting n items triggers copies of 1 + 2 + 4 + … + 2⌊log₂(n−1)⌋ < 2n elements (geometric series), plus n writes, so the total is < 3n and each append costs O(1) amortized [7].
Accounting method. Charge every insert 3 coins: one pays for the write, two are saved. When the table of size m doubles, the m/2 items inserted since the last doubling have saved m coins — exactly enough to move all m items [7].
CPython's actual policy is not exact doubling: the list implementation over-allocates proportionally to the list size, "mild" but enough for linear-time amortized behaviour over a long sequence of appends [19][9]. Any growth by a constant factor gives amortized O(1); growth by a constant amount (e.g. +10 slots) gives Θ(n²) total.
Time–space trade-offs
Many speed-ups buy time with memory. The duplicate check is the textbook case: the all-pairs version uses Θ(n²) time and Θ(1) space, while the hash-set version uses O(n) average time and O(n) space (Section I). Memoization (Lab 4) stores Θ(n) results to turn exponential time into linear time. Prefix sums store n + 1 numbers so that any range sum takes O(1). The reverse trade also exists: the iterative Fibonacci keeps only two variables, Θ(1) space, by recomputing rather than storing.
IPython implementation
The companion module below implements every example in this chapter from scratch, instruments it with an operation counter so you can see growth rates, and measures time and memory with the standard library. It was executed with CPython 3 to produce the outputs shown.
I.1 The instrumentation idea
Instead of a stopwatch, each function receives an OpCounter and calls c.tick() once per basic operation (the comparison in the innermost loop). This is the "count the inner loop" method from Princeton [5] turned into code.
class OpCounter:
"""Counts 'basic operations' so we can see growth without a stopwatch."""
def __init__(self):
self.ops = 0
def tick(self, k=1):
self.ops += k
I.2 One function per complexity class
def get_first(a, c): # Θ(1): one index, independent of n
c.tick()
return a[0] if a else None
def binary_search(a, target, c): # O(log n): interval halves each pass
lo, hi = 0, len(a) - 1 # invariant: target, if present, is in a[lo..hi]
while lo <= hi:
c.tick()
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 # discard left half
else:
hi = mid - 1 # discard right half
return -1
def has_duplicate_quadratic(a, c): # O(n²) time, O(1) extra space
n = len(a)
for i in range(n):
for j in range(i + 1, n): # triangular loop: n(n-1)/2 pairs
c.tick()
if a[i] == a[j]:
return True
return False
def has_duplicate_set(a, c): # O(n) average time, O(n) extra space
seen = set()
for x in a:
c.tick()
if x in seen: # O(1) average membership test
return True
seen.add(x)
return False
Line notes. In binary_search, the loop invariant "if the target is present it lies in a[lo..hi]" is what makes discarding half the array safe; each iteration shrinks hi − lo + 1 to at most half, so there are at most ⌊log₂ n⌋ + 1 iterations [1]. (lo + hi) // 2 cannot overflow in Python because integers have unbounded precision; in fixed-width languages write lo + (hi − lo) // 2. In has_duplicate_set, x in seen and seen.add(x) are O(1) on average and O(n) in the worst case [9].
I.3 Space: recursion versus iteration, and exponential versus linear
def sum_recursive(a, i=0): # O(n) time, O(n) call-stack space
if i == len(a): # base case
return 0
return a[i] + sum_recursive(a, i + 1)
def sum_iterative(a): # O(n) time, O(1) auxiliary space
total = 0
for x in a:
total += x
return total
def fib_naive(n, c): # Θ(φⁿ) time, Θ(n) stack
c.tick()
if n < 2:
return n
return fib_naive(n - 1, c) + fib_naive(n - 2, c)
def fib_iter(n): # Θ(n) time, Θ(1) auxiliary space
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
I.4 A dynamic array from scratch, with amortized accounting
class DynamicArray:
"""Doubling array: append is O(1) amortized, O(n) worst case."""
def __init__(self):
self._cap, self._n = 1, 0
self._data = [None] * self._cap
self.copies = 0 # element moves caused by resizing
def __len__(self):
return self._n
def __getitem__(self, i):
if not 0 <= i < self._n: # error handling: reject out-of-range
raise IndexError("DynamicArray index out of range")
return self._data[i]
def append(self, x):
if self._n == self._cap: # full → grow by a constant FACTOR
self._resize(2 * self._cap)
self._data[self._n] = x
self._n += 1
def _resize(self, new_cap): # Θ(n): copy every element
new = [None] * new_cap
for k in range(self._n):
new[k] = self._data[k]
self.copies += 1
self._data, self._cap = new, new_cap
I.5 Measuring instead of guessing
The standard library provides time.perf_counter/timeit for timing [17] and tracemalloc for tracing memory allocations, including the peak size of traced blocks [20]. The doubling experiment reproduces Princeton's method: if T(n) ∼ c·nb, then T(2n)/T(n) → 2b [5].
def peak_bytes(fn, *args):
tracemalloc.start()
fn(*args)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def doubling_experiment(fn, sizes):
prev, rows = None, []
for n in sizes:
data = list(range(n))
t0 = time.perf_counter(); fn(data); t = time.perf_counter() - t0
rows.append((n, t, None if prev is None else t / prev))
prev = t
return rows
I.6 Sample run — actual output
Running the complete module (I.10) printed the following. Timing numbers vary by machine; the ratios are what matter.
== Operation counts ==
n= 8 O(1)=1 O(log n)=3 O(n)=7 O(n log n)=12 O(n^2)=28
n= 16 O(1)=1 O(log n)=4 O(n)=15 O(n log n)=32 O(n^2)=120
n= 32 O(1)=1 O(log n)=5 O(n)=31 O(n log n)=80 O(n^2)=496
n= 64 O(1)=1 O(log n)=6 O(n)=63 O(n log n)=192 O(n^2)=2016
== Fibonacci calls ==
fib(10)=55 naive calls=177 memo calls=19 iter=55
fib(20)=6765 naive calls=21891 memo calls=39 iter=6765
fib(25)=75025 naive calls=242785 memo calls=49 iter=75025
== Duplicates ==
False 499500 False 1000
== Recursion depth ==
limit: 1000
sum_iterative(10**5): 4999950000
sum_recursive(10**5): RecursionError: maximum recursion depth exceeded
== Dynamic array ==
n= 8 copies= 7 (n+copies)/n = 1.875
n= 16 copies= 15 (n+copies)/n = 1.938
n= 1000 copies= 1023 (n+copies)/n = 2.023
n=100000 copies=131071 (n+copies)/n = 2.311
== Peak memory (tracemalloc) ==
list(range(10**5)) bytes ~ 3991952
sum generator bytes ~ 456
== Doubling experiment: quadratic dup check ==
n= 500 t=0.0063s ratio=None
n= 1000 t=0.0274s ratio=4.36
n= 2000 t=0.1059s ratio=3.86
- Each doubling of n adds 1 to the binary-search count, roughly doubles the linear count, and roughly quadruples the quadratic count (28 → 120 → 496 → 2016 is exactly n(n−1)/2).
- Naive Fibonacci calls grow ≈ 11× from n = 20 to 25 (φ⁵ ≈ 11.09); memoized calls grow by 10 (2n − 1).
- For 1,000 distinct items the brute-force check does 499,500 comparisons; the set version does 1,000.
(n + copies)/nstays below 3 — the amortized bound from Section H.- The quadratic routine's time ratio is ≈ 4 when n doubles, matching 2² [5].
- Materialising
list(range(10⁵))peaks near 4 MB; summing a generator peaks under 1 KB — Θ(n) vs Θ(1) space.
I.7 Dry-run tables
Dry run 1 · binary_search([1, 3, 5, 7, 9, 11, 13, 15], 12)
| Iteration | lo | hi | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 7 | 7 < 12 → lo = 4 |
| 2 | 4 | 7 | 5 | 11 | 11 < 12 → lo = 6 |
| 3 | 6 | 7 | 6 | 13 | 13 > 12 → hi = 5 |
| — | 6 | 5 | — | — | lo > hi → return −1 (3 comparisons ≤ ⌊log₂ 8⌋ + 1 = 4) |
Dry run 2 · has_duplicate_set([3, 1, 4, 1, 5])
| Step | x | seen before | x in seen? | Action |
|---|---|---|---|---|
| 1 | 3 | {} | False | add 3 |
| 2 | 1 | {3} | False | add 1 |
| 3 | 4 | {1, 3} | False | add 4 |
| 4 | 1 | {1, 3, 4} | True | return True after 4 ticks |
Dry run 3 · DynamicArray: appending 1 … 9
| Append # | cap before | Resize? | Copies this step | Total copies | Total cost (writes + copies) |
|---|---|---|---|---|---|
| 1 | 1 | no | 0 | 0 | 1 |
| 2 | 1 | → 2 | 1 | 1 | 3 |
| 3 | 2 | → 4 | 2 | 3 | 6 |
| 4 | 4 | no | 0 | 3 | 7 |
| 5 | 4 | → 8 | 4 | 7 | 12 |
| 6–8 | 8 | no | 0 | 7 | 15 |
| 9 | 8 | → 16 | 8 | 15 | 24 (24 / 9 ≈ 2.67 < 3) |
I.8 Edge cases and error handling
find_max([])raisesValueError, mirroring the built-inmax([]); an empty input is a correctness question, not a complexity question.DynamicArray.__getitem__raisesIndexErrorfor negative or too-large indices instead of reading stale slots.sum_recursive(list(range(10**5)))raisesRecursionErrorunder the default recursion limit — Θ(n) stack space is a real failure mode, not just a number [11].binary_searchrequires sorted input; on unsorted input it is fast and wrong.
I.9 Built-in alternatives and how they compare
| Task | From scratch (this chapter) | Built-in | Complexity |
|---|---|---|---|
| Maximum | find_max | max(a) | Θ(n) both; built-in loop runs in C [9] |
| Search sorted list | binary_search | bisect.bisect_left(a, x) | O(log n) [22] |
| Membership | linear scan | x in set_ | O(n) list vs O(1) average set [9] |
| Sorting | merge_sort | sorted(a), a.sort() | O(n log n); O(n) on presorted input [9] |
| Memoization | dict-based fib_memo | @functools.cache / lru_cache | trades O(n) memory for time [23] |
| Queue | list.pop(0) | collections.deque.popleft() | O(n) vs O(1) [12] |
| Timing | perf_counter loop | timeit | — [17] |
I.10 The complete, runnable module
Save as complexity_examples.py and run with python3 complexity_examples.py.
"""Chapter: Time and Space Complexity — runnable companion code."""
import sys, time, tracemalloc
from functools import lru_cache
# ---------- 1. Instrumented step counter ----------
class OpCounter:
"""Counts 'basic operations' so we can see growth without a stopwatch."""
def __init__(self):
self.ops = 0
def tick(self, k=1):
self.ops += k
def get_first(a, c): # O(1)
c.tick()
return a[0] if a else None
def find_max(a, c): # Θ(n)
if not a:
raise ValueError("find_max() of empty sequence")
best = a[0]
for x in a[1:]:
c.tick() # one comparison per remaining element
if x > best:
best = x
return best
def binary_search(a, target, c): # O(log n)
lo, hi = 0, len(a) - 1
while lo <= hi:
c.tick()
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
def merge_sort(a, c): # Θ(n log n) time, Θ(n) aux space
if len(a) <= 1:
return a[:]
mid = len(a) // 2
left, right = merge_sort(a[:mid], c), merge_sort(a[mid:], c)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
c.tick()
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
out.extend(left[i:]); out.extend(right[j:])
return out
def has_duplicate_quadratic(a, c): # O(n^2) time, O(1) aux space
n = len(a)
for i in range(n):
for j in range(i + 1, n):
c.tick()
if a[i] == a[j]:
return True
return False
def has_duplicate_set(a, c): # O(n) average time, O(n) aux space
seen = set()
for x in a:
c.tick()
if x in seen:
return True
seen.add(x)
return False
# ---------- 2. Exponential vs linear: Fibonacci ----------
def fib_naive(n, c): # Θ(φ^n) time, Θ(n) stack space
c.tick()
if n < 2:
return n
return fib_naive(n - 1, c) + fib_naive(n - 2, c)
def fib_memo(n, c, memo=None): # Θ(n) time, Θ(n) space
if memo is None:
memo = {}
c.tick()
if n < 2:
return n
if n in memo:
return memo[n]
memo[n] = fib_memo(n - 1, c, memo) + fib_memo(n - 2, c, memo)
return memo[n]
def fib_iter(n): # Θ(n) time, Θ(1) aux space
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# ---------- 3. Space: recursion stack vs loop ----------
def sum_recursive(a, i=0): # O(n) call-stack space
if i == len(a):
return 0
return a[i] + sum_recursive(a, i + 1)
def sum_iterative(a): # O(1) auxiliary space
total = 0
for x in a:
total += x
return total
# ---------- 4. Dynamic array with amortized-cost accounting ----------
class DynamicArray:
"""Doubling array: append is O(1) amortized, O(n) worst case."""
def __init__(self):
self._cap, self._n = 1, 0
self._data = [None] * self._cap
self.copies = 0 # element moves caused by resizing
def __len__(self):
return self._n
def __getitem__(self, i):
if not 0 <= i < self._n:
raise IndexError("DynamicArray index out of range")
return self._data[i]
def append(self, x):
if self._n == self._cap:
self._resize(2 * self._cap)
self._data[self._n] = x
self._n += 1
def _resize(self, new_cap):
new = [None] * new_cap
for k in range(self._n):
new[k] = self._data[k]
self.copies += 1
self._data, self._cap = new, new_cap
def peak_bytes(fn, *args):
tracemalloc.start()
fn(*args)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def doubling_experiment(fn, sizes):
prev = None
rows = []
for n in sizes:
data = list(range(n))
t0 = time.perf_counter(); fn(data); t = time.perf_counter() - t0
rows.append((n, t, None if prev is None else t / prev))
prev = t
return rows
if __name__ == "__main__":
print("== Operation counts ==")
for n in (8, 16, 32, 64):
a = list(range(n))
cs = [OpCounter() for _ in range(5)]
get_first(a, cs[0]); find_max(a, cs[1]); binary_search(a, -1, cs[2])
merge_sort(a[::-1], cs[3]); has_duplicate_quadratic(a, cs[4])
print(f"n={n:>3} O(1)={cs[0].ops} O(log n)={cs[2].ops} O(n)={cs[1].ops}"
f" O(n log n)={cs[3].ops} O(n^2)={cs[4].ops}")
print("\n== Fibonacci calls ==")
for n in (10, 20, 25):
c1, c2 = OpCounter(), OpCounter()
r1 = fib_naive(n, c1); r2 = fib_memo(n, c2)
print(f"fib({n})={r1} naive calls={c1.ops} memo calls={c2.ops} iter={fib_iter(n)}")
print("\n== Duplicates ==")
a = list(range(1000)); c1, c2 = OpCounter(), OpCounter()
print(has_duplicate_quadratic(a, c1), c1.ops, has_duplicate_set(a, c2), c2.ops)
print("\n== Recursion depth ==")
print("limit:", sys.getrecursionlimit())
print("sum_iterative(10**5):", sum_iterative(list(range(10**5))))
try:
sum_recursive(list(range(10**5)))
except RecursionError as e:
print("sum_recursive(10**5): RecursionError:", e)
print("\n== Dynamic array ==")
for n in (8, 16, 1000, 10**5):
d = DynamicArray()
for i in range(n): d.append(i)
print(f"n={n:>6} copies={d.copies:>6} (n+copies)/n = {(n + d.copies)/n:.3f}")
print("\n== Peak memory (tracemalloc) ==")
print("list(range(10**5)) bytes ~", peak_bytes(lambda: list(range(10**5))))
print("sum generator bytes ~", peak_bytes(lambda: sum(i for i in range(10**5))))
print("\n== Doubling experiment: quadratic dup check ==")
for n, t, r in doubling_experiment(lambda d: has_duplicate_quadratic(d, OpCounter()), [500, 1000, 2000]):
print(f"n={n:>5} t={t:.4f}s ratio={r if r is None else round(r,2)}")
JReal-world applications
Complexity is not an exam topic that disappears after graduation; it is how engineers reason about whether a system will survive growth. Princeton's course names the primary practical reason for analysis bluntly: avoiding performance bugs, where a client gets poor performance because a programmer did not understand performance characteristics [6].
- Without an index the database must inspect rows until it finds id = 52 — every row in the worst case (red = wasted reads).
- A balanced search tree keyed on
idcompares against one node per level, so the path length is the tree height (orange path). - Height of a balanced tree with branching factor ≥ 2 is O(log n).
| Domain | Where complexity decides the outcome |
|---|---|
| Backend engineering | Illustration A request handler that checks each of n incoming IDs with id in allowed_list is O(n·m); converting allowed_list to a set makes it O(n + m) on average [9]. The "N + 1 queries" anti-pattern (one query per row instead of one batched query) is the same mistake at the network level: cost grows linearly in round trips. |
| Databases | Indexed lookups follow a balanced tree (O(log n)) instead of scanning (O(n)) — Figure J.1 [1]. Sorting-based operations such as ORDER BY or merge joins inherit the Ω(n log n) comparison-sorting lower bound unless an index already provides order [1]. |
| Operating systems & runtimes | Call stacks are finite. CPython's recursion limit exists to stop runaway recursion from overflowing the C stack and crashing the interpreter [11], so an algorithm's O(depth) stack space is an operational constraint, not just a theoretical one. |
| Networking & security | Hash tables are O(1) only on average; when every key collides, operations become O(n) [9]. Attackers exploited this against web frameworks with crafted keys; Python responded by adding PYTHONHASHSEED hash randomization to protect against denial-of-service from worst-case dict behaviour [21]. |
| Distributed systems | Illustration Any "every node talks to every node" protocol sends Θ(n²) messages per round; at 10 nodes that is 90 messages, at 1,000 nodes nearly a million — which is why large clusters prefer designs whose per-round cost is linear or logarithmic in cluster size. |
| Search engines | Illustration Search is dominated by sorted structures: binary search and merging of sorted lists are O(log n) and O(n + m) respectively [1], which is what makes querying web-scale collections feasible without scanning every document. |
| Web applications | Front-end lists that re-filter all n items on every keystroke are O(n) per keystroke; adding a nested lookup inside the filter silently makes it O(n²). Profiling plus complexity reasoning finds these quickly. |
| Large-scale software | Capacity planning uses the doubling hypothesis: measure at n and 2n, infer the exponent from the ratio, and predict cost at 10n before it ships [5][6]. |
KComparison with alternative approaches
K.1 Ways to judge an algorithm's cost
| Approach | What it gives | Strength | Weakness | Use when |
|---|---|---|---|---|
| Asymptotic analysis (O/Ω/Θ) | growth class | machine-independent, predicts scaling [3] | hides constants and small-n behaviour [14] | choosing an algorithm / data structure |
| Tilde / exact counting | leading term with constant, e.g. ∼ n³/6 | compares algorithms in the same class [5] | more work to derive | tuning two Θ(n log n) options |
| Empirical benchmarking | seconds on real hardware | includes caches, interpreter, constants [5] | machine-specific; can't extrapolate safely | final selection, regressions |
| Doubling experiments | empirical exponent b in T ∼ c·nb | bridges theory and measurement [5] | needs large enough n | checking a hypothesis about growth |
| Amortized analysis | cost per operation over a sequence | tight bounds for resizing structures [7] | single operations can still be slow | throughput-oriented workloads |
| Average / expected analysis | cost under an input distribution or random choices | realistic for hashing, quicksort [1] | adversarial inputs can break it | inputs are random or randomized |
K.2 Three solutions to one problem: "does the list contain a duplicate?"
| Solution | Time | Aux. space | Modifies input? | Choose it when… |
|---|---|---|---|---|
| All pairs | Θ(n²) worst | Θ(1) | no | n is tiny or memory is extremely tight |
| Sort, then compare neighbours | O(n log n) | O(1)–O(n) (in-place vs sorted() copy) | yes, if sorted in place | items are orderable but not hashable, or memory is limited |
| Hash set | O(n) average, O(n²) worst | O(n) | no | default choice for hashable items [9] |
LCommon mistakes and misconceptions
L.1 Hidden linear work inside a loop
result = []
for x in items: # n times
if x in banned_list: # O(m) scan!
result.append(x)banned = set(banned_list) # O(m) once
result = [x for x in items
if x in banned] # O(1) avgx in list is O(n), x in set is O(1) on average [9].
L.2 Using a list as a queue
queue = [start]
while queue:
node = queue.pop(0) # shifts allfrom collections import deque
queue = deque([start])
while queue:
node = queue.popleft()list.pop(k) costs O(n − k), so pop(0) is O(n) [9]; deque.popleft() is O(1) [12]. Over a BFS of n nodes this is the difference between O(n²) and O(n).
L.3 Slicing in recursion
def bs(a, t):
if not a: return False
m = len(a) // 2
if a[m] == t: return True
return bs(a[m+1:], t) if a[m] < t \
else bs(a[:m], t) # copies!def bs(a, t, lo=0, hi=None):
hi = len(a) - 1 if hi is None else hi
if lo > hi: return False
m = (lo + hi) // 2
if a[m] == t: return True
return bs(a, t, m+1, hi) if a[m] < t \
else bs(a, t, lo, m-1)A slice a[i:j] costs O(j − i) [9], so the left version copies n/2 + n/4 + … ≈ n elements: Θ(n) time and Θ(n) extra memory, despite doing only O(log n) comparisons.
L.4 Complexity misconceptions
| Misconception | Correction |
|---|---|
| "Big-O means worst case." | O is an upper bound on a function; worst/best/average choose the function. You can give an O bound on the best case [1]. |
| "O(n) means exactly proportional to n." | O is only an upper bound; 3n + 4 is O(n²) too. Use Θ when you mean "exactly this order". NIST's dictionary notes Big-O is often misused to mean "equal to" [15]. |
| "Two nested loops ⇒ O(n²)." | Only if both run Θ(n) times. An inner halving loop gives O(n log n); a two-pointer inner loop whose pointer never resets gives O(n) total. |
| "O(n/2) is better than O(n)." | Constants are dropped: O(n/2) = O(n) [4]. |
| "Dict lookups are always O(1)." | Average O(1); worst case O(n) when keys collide [9]. |
| "Recursion uses no extra memory." | Each active call holds a stack frame: depth d ⇒ Θ(d) space (Figure F.1). |
| "Amortized O(1) means every call is fast." | Individual appends can be O(n); only the sequence average is bounded [9][7]. |
| "With two inputs, write O(n)." | Keep both variables: merging lists of sizes n and m is O(n + m); a grid is O(rows·cols). |
L.5 Boundary-condition and interview mistakes
- Forgetting output size. Generating all subsets of n items must write 2ⁿ subsets of average length n/2, so it is Ω(n·2ⁿ) no matter how clever the code.
- Not defining n. In an interview, say "let n be the length of the string and k the alphabet size" before giving a bound.
- Ignoring space. Always state both: "O(n) time, O(1) extra space excluding the output."
- Off-by-one in logs. Binary search does at most ⌊log₂ n⌋ + 1 comparisons, not log₂ n (Lab 3 shows both).
- Measuring a cold run once. Repeat timings and compare ratios, as
timeitencourages [17].
MInterview preparation
M.1 Questions interviewers actually ask
- What is the time and space complexity of your solution? Can you do better?
- What is the difference between O, Ω and Θ? Between worst-case and amortized?
- Why is
list.appendO(1) if the list sometimes resizes? - What is the space complexity of a recursive DFS on a path-shaped tree of n nodes?
- Your hash-map solution is O(n) — when could it be O(n²)?
M.2 Pattern: read the constraints, infer the target complexity
Illustration A widely used rule of thumb, assuming roughly 10⁸ simple operations per second and a 1-second limit (a pure-Python solution manages far fewer, so aim one row lower):
| n up to | Feasible complexity | Typical technique |
|---|---|---|
| 10–12 | O(n!) | permutations, brute force |
| 20–25 | O(2ⁿ), O(n·2ⁿ) | subsets, bitmask DP |
| ≈ 500 | O(n³) | triple loops, Floyd–Warshall |
| ≈ 5,000 | O(n²) | 2-D DP, all pairs |
| 10⁵ – 10⁶ | O(n log n) | sorting, heaps, binary search |
| 10⁷ – 10⁸ | O(n) | one pass, two pointers, hashing |
| > 10⁹ | O(log n) or O(1) | math, binary search on the answer |
M.3 Practice problems
Easy · LeetCode 217 — Contains Duplicate Easy
Return True if any value appears at least twice.
Hint
Compare the three approaches in K.2. Which one is O(n)?Optimized approach & complexity
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
O(n) average time, O(n) space. Brute force is Θ(n²)/Θ(1); sorting is O(n log n).Easy · LeetCode 1 — Two Sum Easy
Return indices of two numbers that add up to target.
Hint
For each x, the partner you need istarget − x. Can you check for it in O(1)?Optimized approach & complexity
def two_sum(nums, target):
index_of = {}
for i, x in enumerate(nums):
if target - x in index_of:
return [index_of[target - x], i]
index_of[x] = i
return []
O(n) average time, O(n) space, versus Θ(n²) for checking all pairs.Medium · LeetCode 53 — Maximum Subarray Medium
Find the contiguous subarray with the largest sum.
Hint 1
Brute force over all (i, j) pairs is O(n²) with running sums, O(n³) without.Hint 2
The best subarray ending at i either extends the best one ending at i − 1 or starts fresh at i.Optimized approach & complexity (Kadane)
def max_subarray(nums):
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
Θ(n) time. Note nums[1:] copies: Θ(n) extra space; iterate with indices for Θ(1). A divide-and-conquer version satisfies T(n) = 2T(n/2) + Θ(n) ⇒ Θ(n log n).Medium · LeetCode 3 — Longest Substring Without Repeating Characters Medium
Hint
Keep a window [left, right]. Each pointer only moves forward. How many total moves is that?Optimized approach & complexity
def length_of_longest_substring(s):
last = {}
left = best = 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
O(n) time: right moves n times and left only jumps forward. Space O(min(n, k)) for alphabet size k. This is the "nested-looking but linear" pattern from L.4.Hard · LeetCode 4 — Median of Two Sorted Arrays Hard
The required runtime is O(log(m + n)).
Hint 1
Merging is O(m + n). The log requirement means you must binary-search something.Hint 2
Binary-search a cut position i in the shorter array; the cut j in the other array is then forced so that the left halves have (m + n + 1) // 2 elements.Optimized approach & complexity
def find_median_sorted_arrays(A, B):
if len(A) > len(B):
A, B = B, A
m, n = len(A), len(B)
half = (m + n + 1) // 2
lo, hi = 0, m
INF = float("inf")
while lo <= hi:
i = (lo + hi) // 2
j = half - i
a_left = A[i - 1] if i > 0 else -INF
a_right = A[i] if i < m else INF
b_left = B[j - 1] if j > 0 else -INF
b_right = B[j] if j < n else INF
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return max(a_left, b_left)
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1
else:
lo = i + 1
O(log min(m, n)) time, O(1) space — the search runs only over the shorter array.M.4 Self-check: what is the complexity?
NAdvanced concepts
N.1 The potential method
The most general amortization technique assigns a potential Φ to the data structure's state and defines amortized cost = actual cost + Φ(after) − Φ(before); summing telescopes to actual total + Φ(final) − Φ(initial), so any Φ that starts at 0 and stays non-negative yields valid bounds [7][18]. For a doubling table, Φ = 2·size − capacity works: cheap inserts raise Φ by 2, and a resize's Θ(n) copying is paid for by the drop in Φ.
N.2 Expected time of randomized algorithms
Randomized quicksort runs in expected O(n log n) on every input, because the randomness lives in the algorithm, not the data; its worst case remains Θ(n²) [1]. This differs from average-case analysis, which assumes a distribution over inputs.
N.3 Lower bounds: proving you can't do better
Any comparison-based sorting algorithm needs Ω(n log n) comparisons in the worst case, by the decision-tree argument: there are n! possible orderings, a binary decision tree with n! leaves has height ≥ log₂(n!) = Θ(n log n) [1]. So merge sort is asymptotically optimal among comparison sorts; beating n log n requires extra assumptions (e.g. integer keys for counting or radix sort) [1].
N.4 Input size in bits and pseudo-polynomial time
Complexity is measured in the size of the input. A loop for d in range(2, N) that tests whether N is prime is O(N) — linear in the value, but the input is only b ≈ log₂ N bits long, so it is O(2b): exponential in the input size. Algorithms polynomial in a numeric value but not in its bit length are called pseudo-polynomial (the classic 0/1-knapsack DP is O(n·W)). MIT 6.006 defines efficiency as polynomial time with respect to the input size [2].
N.5 Multi-parameter and output-sensitive bounds
Graph algorithms are stated in V and E (BFS/DFS: O(V + E)) [1]; string matching in text length and pattern length; and output-sensitive algorithms include the output size k, e.g. reporting all k points in a range. Collapsing these into one "n" loses information.
N.6 Beyond the RAM model
The word-RAM charges every memory access the same O(1) [2], but real hardware has caches and disks where locality dominates. External-memory models count block transfers instead — another reason B-trees use wide nodes. MIT's performance-engineering course (6.172) builds on the same divide-and-conquer recurrences used here [8].
ONotebook-ready summary
First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.
A way to measure how the number of steps an algorithm takes grows as the input size n grows. We count steps, not seconds.
How the extra memory it needs grows with n: variables, copies, and the call stack for recursion.
Example: 3n + 5 → O(n)
O = ceiling · Ω = floor · Θ = both (tight)
- Compare different solutions.
- Predict how code scales on big inputs.
- Choose the most efficient approach.
| Big-O | Name | Typical example |
|---|---|---|
| O(1) | Constant | array index, hash lookup |
| O(log n) | Logarithmic | binary search |
| O(n) | Linear | one loop over n items |
| O(n log n) | Linearithmic | merge sort, heap sort |
| O(n²) | Quadratic | nested loops (n × n) |
| O(n³) | Cubic | three nested loops |
| O(2ⁿ) | Exponential | all subsets |
| O(n!) | Factorial | all orderings |
< O(n²) < O(n³) < O(2ⁿ) < O(n!)
def get_first(arr): return arr[0]
def sum_array(arr): total = 0 for x in arr: total += x return total
def print_pairs(arr): for a in arr: for b in arr: print(a, b)
def binary_search(arr, x): lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 ... # keep one half
- A few variables → O(1) extra space.
- A new list / dict of n items → O(n).
- Recursion depth d → O(d) stack space.
- Slicing
arr[a:b]makes a copy.
- Complexity = how cost grows with n.
- Keep the dominant term: 3n² + 5n → O(n²).
- Lower growth = more efficient for large n.
- Always state time and space.
Detailed revision notes
1 · Definitions
Time complexity T(n) = # primitive steps on input of size n (usually worst case).Space complexity S(n) = peak extra memory (variables + copies + call stack).
f = O(g) ⟺ ∃ c>0, n₀: f(n) ≤ c·g(n) ∀ n ≥ n₀ (upper bound)
f = Ω(g) ⟺ ∃ c>0, n₀: f(n) ≥ c·g(n) ∀ n ≥ n₀ (lower bound)
f = Θ(g) ⟺ both (tight: c₁g ≤ f ≤ c₂g)
Limit test: f/g → 0 ⇒ o(g); → const > 0 ⇒ Θ(g); → ∞ ⇒ ω(g)
2 · Core idea
Drop constants & lower terms → keep the growth shape. 3n² + 5n + 2 = Θ(n²).1 ≺ log n ≺ √n ≺ n ≺ n log n ≺ n² ≺ n³ ≺ 2ⁿ ≺ n!
3 · Loop rules
single loop → n · nested (n×n) → n² · j from i+1 → n(n−1)/2 = Θ(n²)i //= 2 → log n · loop × halving → n log n · sequential blocks → max, nested → multiply
4 · Recurrences
T(n/2)+1 → log n · T(n−1)+1 → n · 2T(n/2)+n → n log n · 2T(n−1)+1 → 2ⁿMaster: aT(n/b)+f(n) — compare f with n^(log_b a): smaller → leaves win, equal → ×log n, bigger → f wins
5 · Python costs
list: a[i] O(1) · append O(1)* · pop() O(1) · pop(0)/insert(0) O(n) · x in list O(n) · slice O(k) · sort O(n log n)dict/set: get/set/in O(1) avg, O(n) worst · deque: both ends O(1) (*amortized)
6 · Space
recursion depth d ⇒ Θ(d) stack · default recursion limit 1000 · slicing copies · generator ≈ O(1)7 · Amortized
grow by ×factor ⇒ total copies < 2n ⇒ O(1) per append · grow by +const ⇒ Θ(n²) total8 · Interview takeaways
① define n (and m, V, E) ② state time AND space ③ say best/avg/worst/amortized ④ look for hidden O(n) inside loops ⑤ use constraints to guess the target class ⑥ hashing is avg O(1), not guaranteedPKnowledge assessment
Attempt everything before opening the answer key in P.5.
P.1 Conceptual questions
- Is n² = O(n³)? Is n² = Θ(n³)? Justify each with the definitions.
- Explain why O(log₂ n) and O(log₁₀ n) are the same class but O(2ⁿ) and O(3ⁿ) are not.
- Give an operation whose worst-case cost is O(n) but whose amortized cost is O(1), and explain why the two statements don't contradict each other.
- A recursive function makes 2 calls per invocation and has depth n. Why is its time exponential while its space is only linear?
- Your colleague says "our hash-map solution is O(1) per lookup, so it can never be slow." Give two reasons this is incomplete.
P.2 Dry-run exercises
- Count exactly how many times
work()runs, then give Θ:
for n = 8 and n = 10.for i in range(n): j = 1 while j < n: work() j *= 2 - Trace
binary_search([2, 4, 6, 8, 10, 12, 14], 4): give lo, hi, mid, a[mid] and the decision for each iteration. - Starting from capacity 1 and doubling, how many element copies occur while appending 17 items? What is the total cost (writes + copies) and the cost per append?
P.3 Coding problems
- Pair with difference k. Given a list of distinct integers and k > 0, return whether two elements differ by exactly k. Write an O(n²) version and an O(n) average version; state their space costs.
- Fix the queue. Rewrite this level-order traversal so it runs in O(n) instead of O(n²):
def levels(root): q, out = [root], [] while q: node = q.pop(0) out.append(node.val) q.extend(c for c in (node.left, node.right) if c) return out - Measure it. Write
estimate_exponent(fn, n)that timesfnon inputs of size n and 2n (repeat 5 times, take the minimum) and returns log₂ of the ratio. Use it to check thatsorted()on random data gives roughly 1 and an all-pairs loop gives roughly 2.
P.4 Practical engineering scenario
An internal "find similar customers" endpoint compares every customer against every other customer using a 50-field similarity score. It took 0.4 s when the company had 2,000 customers; there are now 40,000 and growing 10% per month. Product asks whether a bigger server will fix it. Estimate the current runtime, explain what scaling hardware can and cannot do, and propose a redesign with its complexity.
P.5 Answer key
Conceptual answers
- Yes: n² ≤ 1·n³ for n ≥ 1 (c = 1, n₀ = 1). No: Θ would need n² ≥ c·n³, i.e. n ≤ 1/c for all large n — impossible. So n² = O(n³) but n² = o(n³), not Θ.
- log₂ n = log₁₀ n / log₁₀ 2, a constant factor, which O absorbs. But 3ⁿ / 2ⁿ = (1.5)ⁿ → ∞, so no constant c makes 3ⁿ ≤ c·2ⁿ: different classes.
list.append: a single call that triggers a resize copies all n elements (O(n)), but over any sequence of k appends the total is O(k) [9][7]. Worst-case bounds a single operation; amortized bounds the average over a sequence — both are true.- Time counts all nodes of the recursion tree (up to 2ⁿ). Space counts only frames alive simultaneously — a single root-to-leaf path of length n — because a call's frame is freed when it returns (Lab 4).
- (a) O(1) is average; adversarial or poorly-distributed keys make lookups O(n) [9][21]. (b) O hides constants — hashing large keys or a lookup inside an O(n) loop still costs O(n) per request; plus memory is O(n).
Dry-run answers
- The inner loop runs for j = 1, 2, 4, … while j < n, i.e. ⌈log₂ n⌉ times. n = 8: 8 × 3 = 24 calls. n = 10: 10 × 4 = 40 calls. Θ(n log n).
-
Iter lo hi mid a[mid] Decision 1 0 6 3 8 8 > 4 → hi = 2 2 0 2 1 4 found → return 1 - Resizes happen at appends 2, 3, 5, 9, 17 copying 1 + 2 + 4 + 8 + 16 = 31 elements. Total cost = 17 writes + 31 copies = 48; 48 / 17 ≈ 2.82 < 3.
Coding answers
import math, random, time
from collections import deque
# 1. Pair with difference k
def has_pair_diff_slow(nums, k): # Θ(n²) time, Θ(1) space
n = len(nums)
return any(abs(nums[i] - nums[j]) == k
for i in range(n) for j in range(i + 1, n))
def has_pair_diff_fast(nums, k): # O(n) average time, O(n) space
s = set(nums)
return any(x + k in s for x in nums)
# 2. Level order with a deque: O(n) time, O(width) queue space
def levels(root):
if root is None:
return []
q, out = deque([root]), []
while q:
node = q.popleft()
out.append(node.val)
q.extend(c for c in (node.left, node.right) if c)
return out
# 3. Empirical exponent via the doubling hypothesis
def estimate_exponent(fn, n, repeats=5):
def best_time(size):
data = [random.random() for _ in range(size)]
best = float("inf")
for _ in range(repeats):
t0 = time.perf_counter(); fn(data); best = min(best, time.perf_counter() - t0)
return best
return math.log2(best_time(2 * n) / best_time(n))
def all_pairs(a):
c = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
c += 1
return c
print(round(estimate_exponent(sorted, 200_000), 2)) # ≈ 1 (n log n looks ~1.0–1.1)
print(round(estimate_exponent(all_pairs, 1_500), 2)) # ≈ 2
On our run, estimate_exponent(sorted, 200_000) printed 1.11 and estimate_exponent(all_pairs, 1_500) printed 2.0 — consistent with n log n (slightly above 1) and n². Your numbers will vary slightly.
Engineering scenario — model answer
Diagnose. All-pairs comparison is Θ(n²) (n(n−1)/2 pairs × 50 fields). Going from 2,000 to 40,000 customers multiplies n by 20, so time grows by ≈ 20² = 400: 0.4 s × 400 ≈ 160 s per request. With 10% monthly growth, n doubles roughly every 7.3 months, quadrupling the time each doubling [5].
Hardware. A 4× faster server buys exactly one doubling of n — about 7 months — after which the problem returns. Faster machines change the constant, not the class.
Redesign. (1) Answer per-customer queries instead of recomputing all pairs: compare one customer against n others, O(n) per request. (2) Precompute offline in batch jobs, cache results, and refresh incrementally. (3) Index by blocking keys (region, segment) or use approximate nearest-neighbour indexing so each query inspects a small candidate set rather than all n. (4) Measure with a doubling experiment after each change to confirm the new exponent.
QReferences and further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Asymptotic notation (Ch. 3), cost-times analysis, best/worst/average case, recurrences and master method (Ch. 4), randomized quicksort, sorting lower bound, B-trees, BFS/DFS bounds (Sections B, F, G, H, J, K, N).
- MIT OpenCourseWare, 6.006 Introduction to Algorithms (Spring 2020), Lecture 1: Introduction (E. Demaine, J. Ku, J. Solomon). Efficiency as polynomial time, counting fixed-time operations, word-RAM model and w ≥ log n, growth table at n = 1000 (Sections B, D, F, N).
- MIT OpenCourseWare, 6.006 (Fall 2011), Recitation 1: Asymptotic Complexity. Purpose of asymptotic notation, misleading "=" in Θ(x²), hidden constants (Sections B, C, G, K).
- Stanford University, CS 161 (Winter 2023), Lecture 2: MergeSort, Recurrences 101, and Asymptotic Analysis (adapted from V. Williams; N. Anari, M. Charikar). Formal O/Ω/Θ definitions, merge-sort recursion tree, worst-case-as-adversary rationale (Sections B, G, H, L, O).
- R. Sedgewick, K. Wayne, "4.1 Analysis of Algorithms," Computer Science: An Interdisciplinary Approach, Princeton University. Tilde notation, order of growth, inner-loop counting, ThreeSum n(n−1)(n−2)/6, doubling hypothesis (Sections B, C, F, I, J, K, P).
- R. Sedgewick, K. Wayne, COS 226 lecture slides "1.4 Analysis of Algorithms", Princeton University, Fall 2019. Reasons to analyze algorithms, avoiding performance bugs, N-body example, order-of-growth classifications (Sections B, D, J).
- MIT OpenCourseWare, 6.046J Design and Analysis of Algorithms (Spring 2015), Lecture 5: Amortization. Amortized cost definition, aggregate/accounting/potential methods, table doubling (Sections B, G, H, K, L, N, P).
- C. E. Leiserson et al., MIT 6.172 Performance Engineering of Software Systems, "Divide-and-Conquer Recurrences" review slides. Master method for T(n) = aT(n/b) + f(n), recursion-tree derivation (Sections G, N).
- Python Software Foundation, "Time complexity of operations on built-in types", Python 3 documentation. Costs for list/dict/set, amortized append note, dict worst case O(n), adaptive O(n log n) sort, slicing costs (Sections F, H, I, J, K, L, P).
- Python Wiki, "TimeComplexity". CPython list represented internally as an array; other implementations may differ (Sections F, H).
- Python Software Foundation,
sys.setrecursionlimit/getrecursionlimit, Python 3 documentation. Recursion limit and its purpose of preventing C-stack overflow (Sections F, I, J). - Python Software Foundation,
collections.deque, Python 3 documentation. O(1) appends and pops at both ends (Sections H, I, L). - D. E. Knuth, "Big Omicron and Big Omega and Big Theta," ACM SIGACT News 8(2):18–24, 1976. History of O (Bachmann 1894, Landau), proposal of Ω and Θ for computer science (Sections B, G).
- E. Lehman, F. T. Leighton, A. R. Meyer, Mathematics for Computer Science, §13.7 "Asymptotic Notation", MIT OpenCourseWare 6.042J. Big O as the most-used upper bound, Θ and scalability, pitfalls with asymptotic notation (Sections G, H, K).
- P. E. Black (ed.), "big-O notation," Dictionary of Algorithms and Data Structures, NIST. Informal definition and note that Big-O is often misused to mean "equal to" (Section L).
- A. Tomescu, "'Big Oh' notation in terms of limits," MIT 6.006 Recitation 1, Spring 2014. Limit characterizations of o, O, Θ, Ω, ω (Section G).
- Python Software Foundation,
timeit— Measure execution time of small code snippets. Timing methodology and repeated measurements (Sections I, L). - MIT OpenCourseWare, 6.046J (Spring 2012), Lecture 11: Amortized Analysis. Second source for aggregate, accounting and potential methods (Sections H, N).
- F. Lundh, quoting CPython
listobject.c, "Looking for info on Python's memory allocation," python-list, 2005. CPython list over-allocates proportionally to size, giving linear-time amortized appends (Section H). - Python Software Foundation,
tracemalloc— Trace memory allocations. Measuring current and peak traced memory (Section I). - python-dev mailing list, "Issue #13703: oCERT-2011-003: add -R command-line option and PYTHONHASHSEED", 2012. Hash randomization added to protect against denial of service via worst-case dict behaviour (Sections J, P).
- Python Software Foundation,
bisect— Array bisection algorithm. Built-in binary search on sorted lists (Section I). - Python Software Foundation,
functools.lru_cache/cache. Built-in memoization trading memory for time (Section I).
Practice problem sources
LeetCode problems 1, 3, 4, 53 and 217 are linked at their point of use in Section M. Problem statements are owned by their respective sites.