Skip to content

Big O by counting, not memorising

BasicsConcept

O(n²) and O(n log n) look like labels to memorise. They are not: you get them by counting how often the code does its basic step, then keeping only the part of the count that grows fastest.

01 What Big O measures

Big O does not tell you how many seconds code takes; that depends on the machine. It tells you how the amount of work grows as the input grows. If you double n, does the work double, quadruple, or barely change?

So the method is: pick the basic step (a comparison, a lookup, an addition), count how many times it runs for an input of size n, and simplify.

02 One loop: count the trips

total.py
def total(nums):
s = 0
for x in nums: # runs n times
s += x # 1 addition each time
return s

The body runs once per item: n additions, plus a couple of fixed steps before and after. The count is n + 2. Double the list and the work doubles.

03 Nested loops multiply

To check a list for a repeated value the plain way, compare every pair. The inner loop starts just after i, so no pair is compared twice.

pairs.py
def contains_duplicate(nums):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return False
Counting the comparisons for n = 4
Step 1 of 7
n 4
nums
50
21
82
33
  • position i
  • position j, compared

Four numbers and no comparisons yet. Each pair of positions will be compared once.

0 comparisons

In general the inner loop runs n − 1, then n − 2, … down to 0 times. That adds up to n(n − 1) / 2. For n = 4 it is 6, matching the count above.

04 Keep only the term that grows fastest

Multiply out the count: n(n − 1) / 2 = n²/2 − n/2. Now see what each part does as n grows.

The parts of n(n − 1)/2
nn² / 2n / 2Total comparisons
1050545
1005,000504,950
1,000500,000500499,500

The n/2 part becomes a rounding error. Drop it. Then drop the 1/2 in front, because a fixed factor does not change how the work grows: double n and n²/2 still quadruples, just like n². What is left is O(n²).

  • Count the basic step for size n.
  • Keep the term that grows fastest; drop the rest.
  • Drop the constant factor in front of it.

05 Loops in a row add

Two loops one after the other cost n + n = 2n, which is still O(n). Sorting first and then scanning costs n log n + n, and the n log n term wins: O(n log n). Only loops inside loops multiply.

Every pair
def contains_duplicate(nums):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return False
One pass with a set
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
Every pairO(n²)About 500,000 comparisons for 1,000 items.
Sort, then check neighboursO(n log n)Equal values end up next to each other, so one scan finds them.
Hash setO(n) on averageEach in and add takes about the same time however big the set is, on average.

06 Loops you cannot see

A single line can hide a loop. Count it the same way: how many items does that one line touch?

for x in nums: if x in other_list:`in` on a listin on a list checks items one by one, so this is a loop inside a loop: O(n·m). On a set or dict, in is O(1) on average.
while queue: x = queue.pop(0)Removing from the front of a listIn Python, list.pop(0) shifts every remaining item left, so it is O(n) per call and the loop is O(n²). Use collections.deque and popleft().
def f(nums): return f(nums[1:])Slicing copiesnums[1:] builds a new list of n − 1 items. Doing it at every call adds n + (n − 1) + …, which is O(n²). Pass an index instead.
for a in A: for b in B:Two inputs are two lettersThis is O(a·b), not O(n²). If B is always tiny, the work grows like A alone.
i = 1 while i < n: i *= 2A loop that doublesi reaches n after about log₂ n trips, not n. The next tutorial, Where log n comes from, is about this shape.

Big O is about large n. For 10 items, an O(n²) loop doing 45 cheap comparisons can beat an O(n) one that hashes every value. Count first, then measure if it matters.

07 Check yourself

Question

A function runs one loop over n items, then a second, separate loop over the same n items. What is its Big O?

Question

Your count comes out as 3n² + 100n + 7. What is the Big O?

Question

for x in nums: if x in seen_list: … where seen_list grows by one each trip. What is it?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?