Big-O & Complexity
Measure how code scales
A complete, practical guide to Big-O notation in Python β how to read it, how to derive it from real code, and how to use it to pick the right data structure before performance becomes a problem.
def find_duplicates(items): seen = set() # O(1) membership duplicates = [] for item in items: # O(n) loop if item in seen: # O(1) lookup duplicates.append(item) seen.add(item) # O(1) insert return duplicates # Overall: O(n) time, O(n) space
[3, 1]
# 1000 items: ~1 ms Β· 1,000,000 items: ~1 s
π Why Big-O Matters
It predicts how code behaves as inputs grow β before you ship it
Complexity Is About Growth, Not Speed
Big-O notation describes how the cost of an algorithm grows as the input size grows. It doesn't tell you how many milliseconds a function takes β it tells you whether doubling the input doubles the time, quadruples it, or barely changes it at all.
That distinction matters because small inputs hide bad algorithms. A quadratic function that runs in a millisecond on 100 items takes 100 seconds on 10,000 items. You may not notice the problem during development and discover it only when real data arrives.
The practical payoff is choosing the right data structure before you write the code. Knowing that a list lookup is O(n) and a set lookup is O(1) is often the difference between a fast program and a slow one β and it requires no profiling at all, because the answer follows from the structure of the code.
Big-O is an upper bound
Formally, O(f(n)) means "grows no faster than f(n)" β it's a ceiling, not an exact count. Two functions that are both O(n) can differ by a constant factor of 100x. Big-O tells you what happens when the input gets large, not how fast a specific run will be.
- βRead and write Big-O notation for time and space
- βRecognise the common complexity classes and what they mean in practice
- βDerive complexity from real Python code
- βKnow the complexity of Python's built-in data structures
- βUse Big-O to choose between a list, a set, and a dict
- βAvoid the most common hidden-complexity traps in Python
π€ Reading the Notation
What O(1), O(n), and O(nΒ²) actually mean
Big-O describes the shape of the growth curve. The letter n stands for the size of the input β the number of items in a list, the number of characters in a string, the number of nodes in a graph. The expression inside the parentheses says how cost scales with that size.
| Notation | Name | What it means |
|---|---|---|
O(1) | Constant | Cost doesn't change with input size |
O(log n) | Logarithmic | Cost grows slowly β each step halves the problem |
O(n) | Linear | Cost scales directly with input size |
O(n log n) | Linearithmic | Slightly worse than linear β typical of good sorting |
O(nΒ²) | Quadratic | Cost scales with the square β nested loops |
O(2βΏ) | Exponential | Cost doubles with each added input β intractable |
O(n!) | Factorial | Combinatorial explosion β brute-force permutations |
How the curves compare
n = 10 n = 100 n = 1,000 βββββββββββββββββββββββββββββββββββββββββββββββββββββ O(1) 1 1 1 O(log n) 3 7 10 O(n) 10 100 1,000 O(n log n) 33 664 9,966 O(nΒ²) 100 10,000 1,000,000 O(2βΏ) 1,024 10Β³β° impractical
Dropping constants
Big-O ignores constant factors and lower-order terms. Both of the functions below are O(n), even though one does three operations per item and the other does one:
def one_operation_per_item(items): total = 0 for item in items: total += item return total # O(n) β one pass def three_operations_per_item(items): total = 0 for item in items: total += item total += 1 total += 2 return total # Also O(n) β constant factor of 3x, but same growth shape
Dropping constants doesn't mean they don't matter in practice β a 3x difference is real. It means they don't change the shape of the curve, and Big-O is about shape.
Keeping only the dominant term
def mixed_complexity(items): for item in items: # O(n) print(item) for a in items: # O(nΒ²) nested loop for b in items: print(a, b) # Total: O(n) + O(nΒ²) = O(nΒ²) β the dominant term wins
When two terms are added, keep the one that grows faster. O(nΒ² + n) simplifies to O(nΒ²), because for large n the quadratic part dominates.
π·οΈ The Common Complexity Classes
What each one looks like in real code
O(1) β Constant
BestCost is independent of input size. Dictionary lookups, arithmetic, and indexing by position are all O(1).
def first_item(items): return items[0] # O(1) β indexing a list is constant def lookup(mapping, key): return mapping[key] # O(1) β dict lookup def add(a, b): return a + b # O(1) β arithmetic
O(log n) β Logarithmic
ExcellentEach step halves the remaining work. Binary search is the classic example. A 1,000,000-item search takes about 20 steps.
def binary_search(sorted_items, target): lo, hi = 0, len(sorted_items) - 1 while lo <= hi: mid = (lo + hi) // 2 if sorted_items[mid] == target: return mid elif sorted_items[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1 # Each iteration halves the search space: O(log n)
O(n) β Linear
GoodCost scales directly with input size. A single pass over a collection. Doubling the input doubles the time.
def find_max(items): best = items[0] for item in items: # one pass if item > best: best = item return best def sum_all(items): total = 0 for item in items: # one pass total += item return total
O(n log n) β Linearithmic
FairA linear pass that also does logarithmic work per item. This is the complexity of efficient sorting algorithms like merge sort and Python's sorted().
def merge_sort(items): if len(items) <= 1: return items mid = len(items) // 2 left = merge_sort(items[:mid]) right = merge_sort(items[mid:]) return merge(left, right) # log n levels of recursion Γ O(n) merge per level = O(n log n)
O(nΒ²) β Quadratic
SlowNested loops over the same collection. For 10,000 items, that's 100 million operations. Often avoidable with a set or dict.
def find_duplicates_slow(items): duplicates = [] for i in range(len(items)): # O(n) for j in range(i + 1, len(items)): # O(n) inner if items[i] == items[j]: duplicates.append(items[i]) return duplicates # O(nΒ²) β for 10k items, ~50M comparisons
O(2βΏ) β Exponential
Very SlowEach additional input doubles the work. Naive recursive Fibonacci is the textbook example. Only viable for very small inputs.
def fib_naive(n): if n < 2: return n return fib_naive(n - 1) + fib_naive(n - 2) # O(2βΏ) β fib(40) takes about 2 billion calls
sorted() and .sort() use Timsort, which is O(n log n) in the worst case and O(n) on already-sorted data.
πΎ Space Complexity
Memory grows too β measure it the same way
Space complexity describes how memory usage grows with input size. It uses the same notation as time complexity: O(1) means constant extra memory, O(n) means memory proportional to input size, and so on.
# O(1) space β uses a fixed number of variables def sum_in_place(items): total = 0 for item in items: total += item return total # O(n) space β allocates a new list proportional to input def double_all(items): result = [] for item in items: result.append(item * 2) return result # O(n) space β a set can grow to the size of the input def unique_items(items): return list(set(items))
Trading space for time
A common optimization is to spend more memory to save time. The find_duplicates example from the hero is exactly this: a set uses O(n) extra memory, but turns an O(nΒ²) nested loop into an O(n) single pass.
def find_duplicates_slow(items): duplicates = [] for i in range(len(items)): for j in range(i + 1, len(items)): if items[i] == items[j]: duplicates.append(items[i]) return duplicates # Time: O(nΒ²) Β· Space: O(1) extra def find_duplicates_fast(items): seen = set() duplicates = [] for item in items: if item in seen: duplicates.append(item) seen.add(item) return duplicates # Time: O(n) Β· Space: O(n) extra
n levels deep uses O(n) space even if it allocates no other structures. Python's default recursion limit is about 1,000 frames.π Python Data Structure Complexity
The table you'll come back to
Python's built-in collections have well-defined complexity. Knowing these means you can choose the right one without measuring. The table below covers the most common operations.
List
| Operation | Complexity | Notes |
|---|---|---|
items[i] | O(1) | Index access |
items.append(x) | O(1) amortized | Occasionally O(n) for resize |
items.pop() | O(1) | Removes from the end |
items.insert(0, x) | O(n) | Shifts every element |
x in items | O(n) | Linear search |
items.remove(x) | O(n) | Search plus shift |
items.sort() | O(n log n) | Timsort |
Dict
| Operation | Complexity | Notes |
|---|---|---|
d[key] | O(1) average | Hash lookup |
d[key] = value | O(1) average | Hash insert |
key in d | O(1) average | Hash membership |
d.get(key) | O(1) average | Safe lookup |
del d[key] | O(1) average | Hash delete |
for k in d | O(n) | Iteration |
Set
| Operation | Complexity | Notes |
|---|---|---|
x in s | O(1) average | Hash membership |
s.add(x) | O(1) average | Hash insert |
s.remove(x) | O(1) average | Hash delete |
s | t | O(len(s) + len(t)) | Union |
s & t | O(min(len(s), len(t))) | Intersection |
s - t | O(len(s)) | Difference |
Deque (collections.deque)
| Operation | Complexity | Notes |
|---|---|---|
d.append(x) | O(1) | Add to the right |
d.appendleft(x) | O(1) | Add to the left |
d.pop() | O(1) | Remove from the right |
d.popleft() | O(1) | Remove from the left |
d[i] | O(n) | Index access is slow |
x in list is O(n) but x in set is O(1). This single fact accounts for more performance improvements in real Python code than any other. If you're checking membership inside a loop, use a set.
String operations
| Operation | Complexity | Notes |
|---|---|---|
s[i] | O(1) | Index access |
s + t | O(len(s) + len(t)) | Concatenation |
sub in s | O(len(s) Γ len(sub)) | Substring search |
s.split(sep) | O(len(s)) | Splitting |
s.upper() | O(len(s)) | Case conversion |
+= in a loop is O(nΒ²), because each concatenation copies the existing string. Use "".join(parts) instead β it's O(n).π¬ Deriving Complexity From Code
A step-by-step method
The method is simple: count the loops, look at what happens inside them, and combine the pieces. Most real code falls into a handful of patterns once you start looking.
# 1. Single loop over the input: O(n) def count_positive(items): count = 0 for item in items: if item > 0: count += 1 return count # 2. Two sequential loops: O(n) + O(n) = O(n) def count_and_sum(items): count = 0 for item in items: count += 1 total = 0 for item in items: total += item return count, total # 3. Nested loops over the same input: O(nΒ²) def pairs(items): result = [] for a in items: for b in items: result.append((a, b)) return result # 4. Loop that halves: O(log n) def count_doublings(n): steps = 0 while n > 1: n = n // 2 steps += 1 return steps # 5. Loop with a set inside: O(n) def has_duplicates(items): seen = set() for item in items: # O(n) if item in seen: # O(1) return True seen.add(item) return False # 6. Loop with a list search inside: O(nΒ²) def has_duplicates_slow(items): seen = [] for item in items: # O(n) if item in seen: # O(n) return True seen.append(item) return False
The three questions
- How many times does each loop run?
- What is the cost of the operations inside the loop?
- Do the loops nest, or run sequentially?
Nested loops multiply. Sequential loops add. A loop that halves the problem each iteration is logarithmic. A loop with an O(1) operation inside is O(n); a loop with an O(n) operation inside is O(nΒ²).
Hidden complexity in Python
| What looks cheap | Actually | Why |
|---|---|---|
x in some_list | O(n) | Linear scan |
list.insert(0, x) | O(n) | Shifts every element |
s += char in a loop | O(nΒ²) | Each concatenation copies |
some_list[1:] | O(n) | Creates a new list |
list.pop(0) | O(n) | Shifts every element |
sorted(x) inside a loop | O(nΒ² log n) | Sorts on every iteration |
x in items reads like a single operation but is a full scan on a list. Switching to a set is a one-line fix that turns O(nΒ²) into O(n).
Optimizing with the right structure
# Before: O(n Γ m) β for each item in a, scan all of b def common_slow(a, b): result = [] for item in a: if item in b: # O(m) scan of list b result.append(item) return result # After: O(n + m) β build a set once, then O(1) lookups def common_fast(a, b): b_set = set(b) # O(m) one-time cost return [item for item in a if item in b_set] # O(n) total # Even simpler: set intersection is O(min(len(a), len(b))) def common_fastest(a, b): return list(set(a) & set(b))
This is the pattern behind most real-world Python performance fixes: replace a list membership test with a set membership test, or replace a nested loop with a dictionary lookup.
ποΈ Mini Project β Three Ways to Find Duplicates
Measure the difference Big-O predicts
This program implements three versions of "find duplicates" with different complexity classes, then measures them at increasing input sizes so you can see the curves diverge.
import time import random def dupes_quadratic(items): seen = [] dupes = [] for item in items: # O(n) if item in seen: # O(n) list scan dupes.append(item) else: seen.append(item) return dupes # Time: O(nΒ²) def dupes_linear(items): seen = set() dupes = [] for item in items: # O(n) if item in seen: # O(1) set lookup dupes.append(item) else: seen.add(item) return dupes # Time: O(n) def dupes_counter(items): from collections import Counter counts = Counter(items) # O(n) return [item for item, count in counts.items() if count > 1] # Time: O(n) def benchmark(fn, n): data = [random.randint(0, n // 2) for _ in range(n)] start = time.perf_counter() fn(data) return time.perf_counter() - start sizes = [500, 1000, 2000, 4000] print(f"{'n':>8} {'quadratic':>12} {'linear':>12} {'counter':>12}") for n in sizes: t_q = benchmark(dupes_quadratic, n) t_l = benchmark(dupes_linear, n) t_c = benchmark(dupes_counter, n) print(f"{n:>8} {t_q:>11.4f}s {t_l:>11.4f}s {t_c:>11.4f}s")
The output will show the quadratic version growing roughly 4x each time the input doubles, while the linear versions grow roughly 2x. That's the O(nΒ²) versus O(n) signature in raw numbers β and it's exactly what the theory predicted.
β Frequently Asked Questions
Common questions about Big-O and complexity
You need the small subset that covers built-in data structures: list lookup is O(n), set and dict lookup is O(1), nested loops multiply. That subset prevents most performance bugs and requires almost no effort to learn. The full formalism is more useful for algorithm design than for writing application code.
Not necessarily. For small inputs, a simple O(nΒ²) algorithm can be faster than a complex O(n log n) one because of lower constant factors. The problem is that "small" is often larger than you think. If the input might grow, prefer the better complexity; if it's genuinely bounded at a small size, the simpler code is fine.
O(n log n) in the worst case, O(n) on already-sorted data. Python uses Timsort, a hybrid merge-and-insertion sort that exploits existing order. In practice it's one of the fastest general-purpose sorts, which is why you should almost never write your own.
Yes. Each s += x creates a new string and copies all existing characters. Doing this n times copies 1 + 2 + ... + n characters, which is O(nΒ²). Use "".join(parts) instead β it allocates once and copies each piece exactly once, for O(n) total.
Sets are implemented as hash tables. Checking membership computes the hash of the value and jumps directly to the corresponding bucket, which is a constant-time operation. List membership has to scan element by element, which is O(n). The trade-off is that sets use more memory and require hashable elements.
Dict and set operations are O(1) on average but O(n) in the worst case, if every key collides into the same bucket. In practice Python's hash functions make this rare for typical data, but it's the reason the docs say "average" rather than just O(1). For strings specifically, hash randomization (enabled by default) prevents adversarial collision attacks.
Usually time, because users notice slow responses but rarely notice a few extra megabytes. The standard trade is: spend memory to save time. Build a set or dict once, then do O(1) lookups instead of O(n) scans. Exceptions exist β embedded systems, huge datasets, and processes with tight memory limits β but for typical applications, time is the constraint.
Measure it. Write a small benchmark that runs the code at a few input sizes and plots or prints the timings. If doubling the input roughly doubles the time, you have O(n). If it quadruples, you have O(nΒ²). If it barely changes, you probably have O(1) or O(log n). The analysis gives you a hypothesis; the measurement confirms it.
π Where to Go Next
Keep building on what you just learned