Big O Notation
The idea
Big O describes how the number of steps grows as the input size n grows. It ignores the computer's speed and focuses on the shape of the growth.
Common complexities (fastest to slowest)
| Big O | Name | Example | n = 1,000,000 |
|---|---|---|---|
| O(1) | constant | dict lookup, arr[i] | 1 step |
| O(log n) | logarithmic | binary search | ~20 |
| O(n) | linear | one loop | 1,000,000 |
| O(n log n) | linearithmic | good sorting | ~20,000,000 |
| O(n²) | quadratic | nested loops | 10¹² 😱 |
| O(2ⁿ) | exponential | trying every subset | impossible |
Rules for calculating
- Drop constants:
3n + 10→ O(n). - Keep the biggest term:
n² + n→ O(n²). - Loops in a row add, nested loops multiply.
- Different inputs get different letters: two loops over
aandb→ O(a + b).
Space complexity
Big O is also used for memory. Making a copy of a list is O(n) extra space; using a few variables is O(1).
Best, average, worst
Big O usually means the worst case: what's guaranteed even with the most unlucky input.
💡 In interviews, always say the time and space complexity of your solution.
Example
import time
def constant(items): # O(1)
return items[0]
def linear(items): # O(n)
return sum(items)
def quadratic(items): # O(n²) — every pair
count = 0
for a in items:
for b in items:
count += 1
return count
data = list(range(2000))
for fn in (constant, linear, quadratic):
start = time.perf_counter()
fn(data)
print(f"{fn.__name__:<10} {time.perf_counter() - start:.5f}s")
# quadratic is MUCH slower — and gets worse as n grows