Complexity and efficiency · 1 / 15 Theory

What is complexity and Big O notation

Two programs can give the same answer and yet one can take a second and the other a year. The difference is almost never how fast your computer is, but how the algorithm's work grows when the input grows. That is complexity.

Counting steps, not seconds

Measuring seconds depends on the machine. Instead, counting steps (comparisons, additions, accesses) is something you can reason about without running anything. What matters is how that number changes as the input size, which we call n, increases.

def count_linear(n):
    steps = 0
    for _ in range(n):
        steps += 1
    return steps

def count_quadratic(n):
    steps = 0
    for _ in range(n):
        for _ in range(n):
            steps += 1
    return steps

for n in (10, 100, 1000):
    print(n, count_linear(n), count_quadratic(n))
# 10 10 100
# 100 100 10000
# 1000 1000 1000000

When you multiply *n* by 10, the first one does 10 times more work and the second one 100 times more. With 1000 elements the difference is already huge.

Big O notation

Big O notation describes how the number of steps grows ignoring constants and small terms. If an algorithm does 3n + 5 steps, we say it is O(n); if it does n² + 10n, it is O(n²), because for large *n* the larger term dominates.

NotationNameTypical example
O(1)constantAccessing list[i], looking up a key in a dictionary
O(log n)logarithmicBinary search: half is discarded at each step
O(n)linearWalking a list, sum, max, searching with in in a list
O(n log n)nearly linearSorting with sorted()
O(n²)quadraticTwo nested loops over the same list
O(2ⁿ)exponentialSimple recursive Fibonacci, trying all subsets

The order from lowest to highest cost is: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ). Check it with your own hands in Growth table.

How to estimate the complexity of code

  • A simple statement (addition, assignment, index access) is O(1).
  • A loop that goes over the *n* elements is O(n). If it contains another O(1) operation, it is still O(n).
  • A loop inside another one, both over *n*, is O(n · n) = O(n²).
  • A loop that halves at each turn (n //= 2) is O(log n).
  • If the code does one thing and then another, they add up and the larger one rules: O(n) + O(n²) = O(n²).
def example(items):
    total = 0
    for x in items:                  # O(n)
        total += x
    for x in items:                  # O(n²) in total
        for y in items:
            total += x * y
    return total                     # overall: O(n²)

print(example([1, 2, 3]))   # 42

Best case, worst case

The same algorithm can take different times depending on the data. Searching for a value in a list by walking it is O(1) if it is the first one (best case) and O(n) if it is the last one or is not there (worst case). Unless stated otherwise, Big O talks about the worst case.

Memory complexity

You can also measure how much extra memory an algorithm uses. Storing the items already seen in a set costs O(n) memory, but in exchange it saves time. It is the most common trade-off: spend memory to gain speed, as you will see with memoization.