Edexcel International Advanced Level Computer Science, point 15.3.1
Definition
Big O notation describes how the running time (or memory use) of an algorithm grows as the size of the input, , grows. It ignores constants and smaller terms, so that it measures the rate of growth, and doesn't depend on the speed of any particular computer. It usually describes an upper bound on the growth.
Function and why needed
- It lets you compare algorithms fairly (independently of hardware and language).
- It predicts how an algorithm will behave on large inputs: an algorithm that is fine for 100 items may be hopeless for a million.
- It helps you choose the right algorithm (searching and sorting, 5.2 and 15.2).
a. Time complexity classes
| Class | Notation | Growth | Example |
|---|---|---|---|
| Constant | Doesn't change with | Reading items[5], push on a stack |
|
| Logarithmic | Grows very slowly (doubling adds one step) | Binary search | |
| Linear | Proportional to | Linear search, finding the largest | |
| Linearithmic | A little more than linear | Merge sort, quick sort (average) | |
| Polynomial | , ... | to a fixed power | Bubble sort, insertion sort (), three nested loops () |
| Exponential | Doubles with each extra item | Trying every subset, naive recursive Fibonacci |
Growth in numbers
| 10 | 1 | 3 | 10 | 33 | 100 | 1 024 |
| 100 | 1 | 7 | 100 | 664 | 10 000 | |
| 1 000 | 1 | 10 | 1 000 | 9 966 | 1 000 000 |
Order, from best to worst:
Exponential algorithms are only usable for tiny inputs (intractable).
Rules for finding Big O
- Drop constants: becomes .
- Keep only the fastest-growing term: becomes .
- Count loops:
- No loop, a fixed number of steps: .
- One loop over items: .
- A loop inside a loop (both over ): .
- A loop that halves (or doubles) the problem each time: .
- A loop of with an inner halving loop: .
- Consecutive blocks add, so the largest wins: is .
- Recursion: count the calls. One call that halves the input is . Two calls that each reduce by 1 gives .
Determining Big O from code
# O(1): a fixed number of steps
first = items[0]
# O(n): one pass over the data
total = 0
for x in items:
total += x
# O(n^2): a loop inside a loop
for a in items:
for b in items:
print(a, b)
# O(log n): the problem halves each time
n = len(items)
while n > 1:
n = n // 2
# O(n log n): n steps, each with a halving loop
for x in items:
k = len(items)
while k > 1:
k = k // 2
# O(2^n): each call makes two more calls
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Worked analysis:
def has_duplicates(items):
for i in range(len(items)): # n times
for j in range(i + 1, len(items)): # up to n times
if items[i] == items[j]:
return True
return False
- Worst case (no duplicates): about comparisons, so .
- Best case (the first two items match): 1 comparison, so .
b. Best and worst case for common algorithms
| Algorithm | Best case | Worst case |
|---|---|---|
| Linear search | (the target is first) | (last or missing) |
| Binary search | (the target is the middle item) | |
| Bubble sort | (sorted, with early exit) | |
| Insertion sort | (sorted) | (reversed) |
| Merge sort | ||
| Quick sort | (poor pivots) | |
| Hash table lookup | (all collisions) | |
| BST search | (the root) | (unbalanced), if balanced |
| Stack push/pop, queue enqueue/dequeue | ||
| Dijkstra's (simple list) | ||
| Tree/graph traversal | / | / |
Best, average and worst case
- Best case: the input that makes the algorithm fastest.
- Worst case: the input that makes it slowest. Big O is usually given for the worst case, as it is a guarantee.
- Average case: a typical input.
Limitations of Big O
- It hides constants: an algorithm with a large constant can be slower than an one for realistic .
- It is about large : for small lists, a simple sort can beat a complex one.
- It describes time here, but memory (space complexity) matters too (merge sort needs extra).
Worked example
Task: state the Big O time complexity of each, and the best and worst case where they differ.
def last_item(items): # (a)
return items[-1]
def count_negatives(items): # (b)
count = 0
for x in items:
if x < 0:
count += 1
return count
def print_table(n): # (c)
for row in range(1, n + 1):
for col in range(1, n + 1):
print(row * col, end=" ")
print()
- (a) One step regardless of size: .
- (b) A single loop that always visits every item (there is no early exit), so it is in the best and worst case.
- (c) Two nested loops, each running times: steps, so (the same in best and worst case).
Effect of doubling : (a) unchanged, (b) doubles, (c) four times as long.
Exam tip: count the loops and look for halving. State the complexity as , with the best and worst cases when they differ. Drop constants and lower terms. Know the order of the classes. Be able to give the best and worst case for the standard searches and sorts.
Check yourself
What does Big O notation describe?
How the running time (or memory) of an algorithm grows as the input size grows, ignoring constants and smaller terms.
Put these in order from slowest-growing to fastest-growing: O(n²), O(1), O(n), O(log n), O(2ⁿ)
O(1), O(log n), O(n), O(n²), O(2ⁿ).
What is the worst-case Big O of bubble sort and of quick sort?
Both are O(n²) in the worst case (quick sort's average is O(n log n)).
What is the Big O of two nested loops that each run n times?
O(n²).
What is the best-case Big O of a linear search?
O(1), when the target is the first item.