Data Structures & Algorithms · Module 1 · Lesson 21 min read

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 ONameExamplen = 1,000,000
O(1)constantdict lookup, arr[i]1 step
O(log n)logarithmicbinary search~20
O(n)linearone loop1,000,000
O(n log n)linearithmicgood sorting~20,000,000
O(n²)quadraticnested loops10¹² 😱
O(2ⁿ)exponentialtrying every subsetimpossible

Rules for calculating

  1. Drop constants: 3n + 10 → O(n).
  2. Keep the biggest term: n² + n → O(n²).
  3. Loops in a row add, nested loops multiply.
  4. Different inputs get different letters: two loops over a and b → 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

Python
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