Kodewick
Start learning →
Big O: O(1), O(n), O(n²)2 / 52

Big O: O(1), O(n), O(n²)

Lesson 2 of 52 · Part 1 · Getting started: how fast · about 16 minutes

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.

Common growth rates drawn to scale: O(1) is flat, O(log n) creeps up, O(n) is a straight line, O(n log n) a little steeper, O(n²) shoots off the chart

What big O says

To get big O from a step formula, you do just two things:

  1. Drop the coefficients: 3n and n are both O(n). Coefficients only differ by a constant factor and the growth is the same: double n and both double.
  2. Keep only the fastest-growing term: n² + 100n + 7 is O(n²). Once n is large, the rest hardly counts.
StepsDrop coefficients and small termsBig O
20a fixed numberO(1)
3n + 2n is leftO(n)
n(n − 1)/2n² is leftO(n²)
n² + 100n + 7n² is leftO(n²)
5n + n² / 1000n² is leftO(n²)
From a step formula to big O: drop the coefficients, keep only the largest term

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.

Choose one

How do you write 3n² + 5n + 100 in big O?

Choose allPick all that apply

Which of these are O(n)? You can pick more than one.

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.

main.py
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))
Output
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.

nums4927501234↑i

Getting nums[3]: the position is worked out directly, no counting from the start
Choose one

n 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.

nums (find x = 7)4925701234↑i
1for i in range(len(nums)):2    if nums[i] == x:3        return i4return -1

Linear search for 7: in the worst case you look at all n, O(n)
main.py
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
Output
(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).

Choose one

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:

O(1)nums[i]1 stepindependent of n
O(n)for x in nums:500 stepsone pass
O(n²)for i… for j…250000 stepsevery one with every one
At n = 500, how many steps each kind of growth takes: O(n²) is 500 times O(n)
main.py
1n = 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)
Output
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²).

Guess the outputA wrong guess is fine

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)
Exercise 1

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.

It should print
True
False
exercise1.py
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]))
Output
Press Run or Ctrl+Enter

Reading big O off the code

You do not have to count every time. Remember three rules:

The code looks likeBig OWhy
One part after anotherthe largest partO(n) + O(n) is still O(n); O(n) + O(n²) is O(n²)
A loop inside a loopmultiplyn outer turns × n inner turns = O(n²); an inner loop of 3 makes O(n)
The size halves each timeO(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]
  1. ①outside the loops, done once: O(1), ignore it
  2. ②outer loop: i from 0 to n − 1, n times
  3. ③for each outer pass, the inner loop runs n times
  4. ④the innermost statement: n × n = n² times
  5. ⑤the part that follows: n times, added to the nested loops
Reading code this way: two loops make n × n, then one more loop makes n, n² + n in all; keep the biggest term: O(n²)

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²):

Count it every turnfor x in nums: if nums.count(x) > 1O(n²)count walks the whole list every time
Sort, then check neighbourss = sorted(nums); s[i] == s[i + 1]O(n log n)sort once, then one pass
Both look like one loop, but in the first one every turn hides an O(n) count

In 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.

Choose one

There is only one for. What is this code in big O?

1total = 02for x in nums:3    total += nums.count(x)
Choose one

Again just one loop. What is it in big O?

1cnt = 02for i in range(n * n):3    cnt += 1
Exercise 2

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.

It should print
110
10100
exercise2.py
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))
Output
Press Run or Ctrl+Enter

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.

Best: find 4looks_for(nums, 4)1 lookthe very first one
Worst: find 6looks_for(nums, 6)5 looksonly after looking at all of them do you know it is not there
The same linear search, looking for different numbers among 4 9 2 5 7

Search for each of the 5 numbers in turn, count the looks each time, and take the average:

main.py
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))
Output
[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.

Guess the outputA wrong guess is fine

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]))
Choose one

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 handleAcceptable big O (roughly)
tensanything, even O(2ⁿ)
thousandsO(n²) is fine
100 thousand to millionsO(n) or O(n log n)
moreO(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):

main.py
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))
Output
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²).

Choose one

You need to check 500,000 order numbers for duplicates. Which way of writing it is right for that?

Summary

Take-away

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²)