Big O: O(1), O(n), O(n²)
Big O says how fast the step count grows with n: drop the coefficients and keep only the fastest-growing term, so 3n + 2 is O(n) and n² + 100n + 7 is O(n²).
The last lesson counted steps: finding the maximum takes n − 1, checking for duplicates n(n − 1)/2. Writing a formula like that every time is long-winded, and we already know the coefficients and the odd bits do not matter once n is large. Big O is the short way to say it: O(n), O(n²). When an interviewer asks "what is the complexity?" or an exam asks for the time complexity, these few characters are what they want. At n = 1 million an O(n) program finishes in under a second and an O(n²) one keeps you waiting more than a day: big O tells you at a glance which kind you have.
What big O says
To get big O from a step formula, you do just two things:
- Drop the coefficients:
3nandnare both O(n). Coefficients only differ by a constant factor and the growth is the same: double n and both double. - Keep only the fastest-growing term:
n² + 100n + 7is O(n²). Once n is large, the rest hardly counts.
| Steps | Drop coefficients and small terms | Big O |
|---|---|---|
| 20 | a fixed number | O(1) |
| 3n + 2 | n is left | O(n) |
| n(n − 1)/2 | n² is left | O(n²) |
| n² + 100n + 7 | n² is left | O(n²) |
| 5n + n² / 1000 | n² is left | O(n²) |
The last row is easy to misread: n²/1000 has a tiny coefficient, but once n passes 5000 it is bigger than 5n. Big O describes what happens once n is large enough.
How do you write 3n² + 5n + 100 in big O?
Which of these are O(n)? You can pick more than one.
n² / 1000 has a tiny coefficient, but it grows like n²: at n = 1 million it is 10⁹, ten times 100n + 50. The other three are all n once the coefficient goes.O(1): nothing to do with n
Reading one element of a list by index works the same however long the list is: the position is computed and the element read directly, with no counting from the start. len(nums) is O(1) too: the list keeps its own length.
1small = list(range(10))2big = list(range(100000))3# both are one step: read by index, no counting from the start4print(small[7], big[99999])5print(len(small), len(big))
7 99999 10 100000
Swapping two variables, working out an expression, return, append to the end of a list: all O(1). The step count is a fixed number and does not change however big n gets.
in is the length of the list. Which code is O(1)?
O(n): one pass
Finding a number in a list means, in the worst case, looking from the first to the last. One loop doing O(1) work per turn is O(n) overall.
i1for i in range(len(nums)):2 if nums[i] == x:3 return i4return -1
1def find(nums, x):2 looks = 03 for i in range(len(nums)):4 looks += 15 if nums[i] == x:6 return i, looks7 return -1, looks8 9nums = [4, 9, 2, 5, 7, 1, 8, 3]10print(find(nums, 4)) # the very first one: the best case11print(find(nums, 3)) # the last one12print(find(nums, 6)) # not there: all n looked at before you can say so
(0, 1) (7, 8) (-1, 8)
With luck it is the first one; without, all 8 are looked at. Complexity usually means the worst case: linear search is O(n).
An O(n) program takes 1 millisecond for n = 1000. About how long for n = 4000?
O(n²): two nested loops
Checking for duplicates by comparing every pair is two nested loops: O(n²). Put the three side by side and count at n = 500:
nums[i]1 stepindependent of nfor x in nums:500 stepsone passfor i… for j…250000 stepsevery one with every one1n = 5002nums = list(range(n))3 4steps = 1 # O(1): read one5print("O(1) ", steps)6 7steps = 08for x in nums: # O(n): one pass9 steps += 110print("O(n) ", steps)11 12steps = 013for i in range(n): # O(n²): every pair i < j14 for j in range(i + 1, n):15 steps += 116print("O(n²)", steps)
O(1) 1 O(n) 500 O(n²) 124750
The third part is n(n − 1)/2 = 124 750 steps, half the n² in the picture: big O ignores that 1/2, both are O(n²).
Two nested loops whose inner one always runs 3 times, then one more loop. What does it print for n = 6?
1n = 62steps = 03for i in range(n):4 for j in range(3):5 steps += 16for k in range(n):7 steps += 18print(steps)
Any duplicates?
✓Finish has_dup: compare every pair with two nested loops (j starts at i + 1), return True as soon as two numbers are equal, and False if none are after all comparisons.
True False
1def has_dup(nums):2 # compare every pair3 return False4 5print(has_dup([3, 8, 1, 9, 8]))6print(has_dup([3, 8, 1, 9, 7]))
Reading big O off the code
You do not have to count every time. Remember three rules:
| The code looks like | Big O | Why |
|---|---|---|
| One part after another | the largest part | O(n) + O(n) is still O(n); O(n) + O(n²) is O(n²) |
| A loop inside a loop | multiply | n outer turns × n inner turns = O(n²); an inner loop of 3 makes O(n) |
| The size halves each time | O(log n) | the next lesson |
cnt = 0①for i in range(n):② for j in range(n):③ if nums[i] == nums[j]: cnt += 1④for k in range(n):⑤ total += nums[k]
- ①outside the loops, done once: O(1), ignore it
- ②outer loop: i from 0 to n − 1, n times
- ③for each outer pass, the inner loop runs n times
- ④the innermost statement: n × n = n² times
- ⑤the part that follows: n times, added to the nested loops
Python needs one more look: a single line can hide a loop. x in nums, nums.count(x), nums.index(x), max(nums) and sum(nums) look like one statement but each walks from start to end: all O(n). Put one inside a loop and you have O(n²):
for x in nums: if nums.count(x) > 1O(n²)count walks the whole list every times = sorted(nums); s[i] == s[i + 1]O(n log n)sort once, then one passIn interviews: asked for the complexity, first find how many times the innermost statement runs, write it in terms of n, then drop coefficients and small terms. Do not miss the in, count, index or slice hidden in a line: that is exactly where interviewers like to dig.
There is only one for. What is this code in big O?
1total = 02for x in nums:3 total += nums.count(x)
nums.count(x) counts through the whole list every time, which is O(n); it sits in a loop that runs n times, so n × n steps in all: O(n²). When you work out big O, the loops hidden in a single line count too.Again just one loop. What is it in big O?
1cnt = 02for i in range(n * n):3 cnt += 1
range(n * n) makes n² passes, so cnt += 1 runs n² times: O(n²).One part after another
✓First one loop runs n times, then two nested loops run n × n times. Finish the counting and print the total steps for n = 10 and n = 100.
110 10100
1def steps_for(n):2 steps = 03 for i in range(n):4 steps += 15 # then two nested loops, n turns each, add 1 to steps each time6 return steps7 8print(steps_for(10))9print(steps_for(100))
Best, worst and average
The same code can take a different number of steps on different data. Take linear search: if the number you want is the very first, one look and you are done; if it is the last, or not there at all, you have to look at all n.
looks_for(nums, 4)1 lookthe very first onelooks_for(nums, 6)5 looksonly after looking at all of them do you know it is not thereSearch for each of the 5 numbers in turn, count the looks each time, and take the average:
1def looks_for(nums, x):2 looks = 03 for v in nums:4 looks += 15 if v == x:6 break7 return looks8 9nums = [4, 9, 2, 5, 7]10counts = [looks_for(nums, x) for x in nums]11print(counts)12print(sum(counts) / len(nums))13print(looks_for(nums, 6))
[1, 2, 3, 4, 5] 3.0 5
- Best case: the data that needs the fewest steps. For linear search that is 1 look, O(1).
- Worst case: the data that needs the most steps. For linear search that is n looks, O(n).
- Average case: if the number is equally likely to be in any position, you look (1 + 2 + … + n) / n = (n + 1) / 2 times on average, still O(n). For 5 numbers that is 3, just what the program printed.
When people say "linear search is O(n)", they mean the worst case: however unlucky you are, it is never slower than that. If a question does not say which case, answer for the worst.
Checking every pair once for a duplicate and returning as soon as one turns up. How many comparisons does this list take?
1def has_dup(nums):2 cmp = 03 for i in range(len(nums)):4 for j in range(i + 1, len(nums)):5 cmp += 16 if nums[i] == nums[j]:7 return cmp8 return cmp9 10print(has_dup([5, 5, 1, 9, 3]))
A linear search over n numbers; the number is certainly in the list, equally likely to be in any position. How many comparisons on average?
How you write it at work
When you finish a piece of code, estimate its big O and look at how big n is:
| The n you handle | Acceptable big O (roughly) |
|---|---|
| tens | anything, even O(2ⁿ) |
| thousands | O(n²) is fine |
| 100 thousand to millions | O(n) or O(n log n) |
| more | O(n), or O(log n) lookups |
The most common fix is to replace the hidden loop. Checking for duplicates does not need every pair: hand it to a set (lesson 4 counts why it is fast):
1def has_dup_slow(nums): # O(n²)2 for i in range(len(nums)):3 if nums[i] in nums[i + 1:]:4 return True5 return False6 7def has_dup(nums): # O(n): the set drops duplicates8 return len(set(nums)) != len(nums)9 10a = [3, 8, 1, 9, 8]11b = [3, 8, 1, 9, 7]12print(has_dup_slow(a), has_dup_slow(b))13print(has_dup(a), has_dup(b))
True False True False
has_dup_slow has only one for, but each turn the slice nums[i + 1:] copies a part first and in walks it again: both O(n), so inside the loop it is O(n²).
You need to check 500,000 order numbers for duplicates. Which way of writing it is right for that?
set removes the duplicates in one pass, O(n), in a blink. The other two each hide an O(n) count, or a slice plus in, inside a loop: O(n²) overall.Summary
Big O: drop the coefficients, keep the fastest-growing term
- O(1): a fixed number of steps; O(n): one pass; O(n²): every one with every one
- Parts one after another: take the largest; loops inside loops: multiply
- An inner loop of a fixed size is not n: two nested loops can be O(n)
- in, count, index, max and slicing each hide an O(n)
- Best, worst and average can differ; if nobody says which, give the worst case
1nums[i]; len(nums) # O(1)2for x in nums: ... # O(n)3for i ...: for j ...: ... # O(n²)4for x in nums: x in nums # also O(n²)