Big-O and complexity
Two programs can give the same answer while one takes a millisecond and the other takes an hour. Data structures (how you organise data) and algorithms (the steps you follow) decide which. This track teaches the classic ones, how to choose between them, and how to solve the problems asked in technical interviews.
Every example in this track is runnable Python. The ideas are the same in every language: once you understand a hash map or binary search here, you can write it in JavaScript, Java or Go.
Counting steps, not seconds
Seconds depend on the computer. Instead, we ask: how does the work grow as the input grows? Say we search a list of n names for one name:
The work grows in proportion to n: ten times more names, ten times more steps. We write that as O(n), "order n", or linear time.
Big-O notation
Big-O describes the growth rate of an algorithm's cost, for large inputs, in the worst case (unless stated otherwise). We keep only the fastest-growing term and drop constants:
3n + 5steps → O(n)n²/2 + nsteps → O(n²)500steps, whatever the input → O(1)
| Big-O | Name | Example | n = 1,000,000 |
|---|---|---|---|
| O(1) | Constant | Read list[i], look up a dict key |
1 |
| O(log n) | Logarithmic | Binary search in a sorted list | ~20 |
| O(n) | Linear | Loop over a list once | 1,000,000 |
| O(n log n) | Linearithmic | Good sorting algorithms | ~20,000,000 |
| O(n²) | Quadratic | Compare every pair (nested loops) | 1,000,000,000,000 |
| O(2ⁿ) | Exponential | Try every subset | more than atoms in the universe |
| O(n!) | Factorial | Try every ordering | even more |
At a billion simple steps per second, the O(n²) column for n = 100,000 takes 10 seconds; O(n log n) takes about 2 milliseconds. That difference is what this whole track is about.
Reading complexity from code
def first(items): # O(1): one step, whatever the length
return items[0]
def total(items): # O(n): one loop over n items
s = 0
for x in items:
s += x
return s
def has_duplicate(items): # O(n²): a loop inside a loop
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return False
def halve_until_one(n): # O(log n): the problem halves each step
steps = 0
while n > 1:
n //= 2
steps += 1
return stepsRules of thumb:
- Sequential steps add: O(n) then O(n) is O(2n) = O(n).
- Nested loops multiply: a loop of n inside a loop of n is O(n²).
- Halving the problem each step gives O(log n).
- Different inputs get different letters: looping over
athenbis O(a + b); nested, O(a × b).
The same problem, three complexities
"Does this list contain two numbers that add up to target?"
The brute-force version does about 4.5 million comparisons; the set version about 3,000 lookups. With 30,000 numbers instead, the brute-force version would take about 100 times longer (n²), the set version only 10 times longer (n).
Space complexity
Memory counts too. pair_sum_set is fast because it stores up to n numbers: O(n) extra space. pair_sum_sorted makes a sorted copy (O(n)), but could sort in place for O(1) extra space. Trading memory for speed is the most common trade-off in this track.
Best, average and worst case
- Worst case: the guarantee (searching for a missing item).
- Average case: what usually happens (quicksort's average O(n log n)).
- Amortised: the average over a sequence of operations. Appending to a Python list is amortised O(1): usually instant, occasionally the list grows and copies itself, but averaged over many appends it's constant.
Practice
- What's the complexity of a function that loops over a list, and inside that loop calls
max()on the same list? - Write
count_steps(n)for a loop that doublesifrom 1 until it reachesn. What Big-O is it? - Which is faster for n = 1,000: 1,000·n steps or n² steps? Which for n = 1,000,000?
1.What is the time complexity of looking at every pair of items in a list?
2.Why do we drop constants, writing O(3n) as O(n)?
3.An algorithm halves the remaining problem at every step. What is its complexity?