B2.4.1 Big O: how efficient is an algorithm?
SL + HLCommand terms: Describe, Calculate1. Calculating Big O, step by step
Big O asks one question: as the input size n grows, how fast does the work grow? Step through three ShelfWise functions: count the operations, then keep only what matters for large n.
2. Growth race
Drag n and watch the complexity classes separate. Click a legend item to hide or show it. The table estimates running time on a computer doing one million operations per second.
3. Operation counter: measure, then classify
Each snippet is run for n = 8, 16, 32, 64 and 128 while every basic operation is counted. Look at what happens to the count when n doubles, then choose its Big O.
4. Will it scale? Choosing an algorithm
ShelfWise must respond within a time limit. Set the catalogue size and the limit, and see which algorithms are still fast enough. The computer does 10 million operations per second.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Classify the code
What is the time complexity of each snippet? Streaks of 3+ score double.
7. 45-second speed round: simplify T(n)
Drop the constants and lower-order terms. What is the Big O?
Expected output
Your analysis
Check my code
time.perf_counter(). Do real timings double and quadruple as the step counts predict? Next task (B2.4.2): linear search versus binary search on the catalogue.Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Count the operations
count_pairs(n) counts how many times the inner line runs in a nested loop over i in range(n) and j in range(n). Write it, print the count for n = 10, 100, 1000, and state the Big O.
Starter file (write your code where it says pass # your code here):
def count_pairs(n):
pass # your code here
# ---- tests ----
for n in [10, 100, 1000]:
print(n, count_pairs(n))
Expected output when your code is correct:
10 100 100 10000 1000 1000000
Hint
Model solution
Counts 100, 10 000, 1 000 000: multiplying n by 10 multiplies the work by 100, so it is O(n²).
def count_pairs(n):
count = 0
for i in range(n):
for j in range(n):
count += 1
return count
# ---- tests ----
for n in [10, 100, 1000]:
print(n, count_pairs(n))
Task 2: Duplicates: two ways
Write has_dup_slow(items) that compares every pair (O(n²)) and has_dup_fast(items) that uses a set (O(n) on average). Count the comparisons the slow version makes for a list with no duplicates of size 1 000, and time both on 5 000 items.
Starter file (write your code where it says pass # your code here):
import time
def has_dup_slow(items):
pass # your code here
def has_dup_fast(items):
pass # your code here
# ---- tests ----
print(has_dup_slow(list(range(1000))))
print(has_dup_fast([3, 1, 4, 1, 5]), has_dup_fast([1, 2, 3]))
data = list(range(5000))
t0 = time.perf_counter(); has_dup_slow(data); t1 = time.perf_counter()
has_dup_fast(data); t2 = time.perf_counter()
print("slow is faster" if t1 - t0 < t2 - t1 else "fast is faster")
Expected output when your code is correct:
(False, 499500) True False fast is faster
This task times code, so speeds vary between computers. The lines printed should still match.
Hint
Model solution
For n items with no duplicate, the slow version makes n(n − 1)/2 comparisons: 499 500 for n = 1 000.
import time
def has_dup_slow(items):
comparisons = 0
for i in range(len(items)):
for j in range(i + 1, len(items)):
comparisons += 1
if items[i] == items[j]:
return True, comparisons
return False, comparisons
def has_dup_fast(items):
seen = set()
for x in items:
if x in seen:
return True
seen.add(x)
return False
# ---- tests ----
print(has_dup_slow(list(range(1000))))
print(has_dup_fast([3, 1, 4, 1, 5]), has_dup_fast([1, 2, 3]))
data = list(range(5000))
t0 = time.perf_counter(); has_dup_slow(data); t1 = time.perf_counter()
has_dup_fast(data); t2 = time.perf_counter()
print("slow is faster" if t1 - t0 < t2 - t1 else "fast is faster")
Task 3: Measure the growth rate
Write ratio_table(func, sizes) that times func(n) for each size and prints the ratio of each time to the previous one. Use doubling sizes. Run it on a linear function (sum of a list) and a quadratic one (count_pairs). From the ratios, decide which is O(n) and which is O(n²). Your timings will differ from the expected output, but the ratios should be near 2 and 4.
Starter file (write your code where it says pass # your code here):
import time
def linear(n):
return sum(range(n))
def quadratic(n):
c = 0
for i in range(n):
for j in range(n):
c += 1
return c
def ratio_table(func, sizes):
pass # your code here
# ---- tests ----
lin = ratio_table(linear, [200000, 400000, 800000, 1600000])
quad = ratio_table(quadratic, [200, 400, 800])
print("linear ratios near 2:", all(1.4 < r < 2.9 for r in lin))
print("quadratic ratios near 4:", all(2.8 < r < 5.5 for r in quad))
Expected output when your code is correct:
linear ratios near 2: True quadratic ratios near 4: True
This task times code, so speeds vary between computers. The lines printed should still match.
Hint
Model solution
import time
def linear(n):
return sum(range(n))
def quadratic(n):
c = 0
for i in range(n):
for j in range(n):
c += 1
return c
def ratio_table(func, sizes):
previous = None
ratios = []
for n in sizes:
best = float("inf")
for _ in range(3):
t0 = time.perf_counter()
func(n)
best = min(best, time.perf_counter() - t0)
if previous:
ratios.append(best / previous)
previous = best
return ratios
# ---- tests ----
lin = ratio_table(linear, [200000, 400000, 800000, 1600000])
quad = ratio_table(quadratic, [200, 400, 800])
print("linear ratios near 2:", all(1.4 < r < 2.9 for r in lin))
print("quadratic ratios near 4:", all(2.8 < r < 5.5 for r in quad))
Learning objectives
By the end of this page you should be able to:
- Describe what Big O notation measures: how the time or memory an algorithm needs grows with the input size n, usually in the worst case.
- Calculate the Big O of an algorithm by counting operations in sequences, loops, nested loops and halving loops, then dropping constants and lower-order terms.
- Identify and order the common classes O(1), O(log n), O(n), O(n log n), O(n²) and O(2ⁿ).
- Distinguish between time complexity and space complexity, and determine the space complexity of simple algorithms.
- Justify the choice of an algorithm based on scalability and efficiency requirements.
What Big O describes
Timing a program in seconds depends on the computer, the language and what else is running. Big O notation instead describes how the number of basic operations (or the memory) grows as the input size n grows. It gives an upper bound, normally for the worst case, and ignores details that stop mattering for large n. That makes it a measure of scalability.
How to calculate it
- Choose n: the size of the input (number of books, length of the list).
- Count basic operations (assignments, comparisons, arithmetic) as a function T(n).
- Statements in sequence: add. A loop over n items: multiply its body by n.
- Nested loops over n: multiply, n × n = n².
- A loop that halves (or doubles) its variable each pass: about log₂ n passes.
- Keep the dominant term and drop constant factors: T(n) = 3n² + 5n + 2 becomes O(n²); 2n + 100 becomes O(n); 500 becomes O(1).
Common classes
| Big O | Name | n doubles, work... | Example |
|---|---|---|---|
| O(1) | Constant | stays the same | Read books[5]; push onto a stack |
| O(log n) | Logarithmic | increases by one step | Binary search; halving loop |
| O(n) | Linear | doubles | Linear search; total of a list |
| O(n log n) | Linearithmic | slightly more than doubles | Merge sort, quicksort (average) |
| O(n²) | Quadratic | quadruples | Bubble and selection sort; comparing every pair |
| O(2ⁿ) | Exponential | squares (adding 1 to n doubles it) | Trying every subset |
From most to least scalable: O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ).
Best, average and worst case
Linear search finds the first item in 1 step (best case) but may need n steps (worst case). Big O is usually quoted for the worst case, because it is a guarantee.
Space complexity
Space complexity is how the extra memory needed grows with n. Reversing a list in place by swapping uses a few variables: O(1) space. Building a reversed copy needs a second list of n items: O(n) space. Recursion also uses space on the call stack (B2.4.4). Often there is a trade-off: using more memory can save time.
Choosing an algorithm
- For large or growing n, the lower complexity class wins, whatever the constants.
- For small n, a simple O(n²) algorithm can be perfectly acceptable, and easier to write and check.
- Consider the requirements: response time, memory available, how often it runs, whether the data is already sorted, and how much the data will grow.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Outline what is meant by the Big O notation of an algorithm. [2]
2. State the Big O time complexity of each fragment, where n is the length of books. [3]
# (a)
print(books[0])
# (b)
for b in books:
print(b)
# (c)
for a in books:
for b in books:
if a == b: print("same")
3. Calculate the time complexity of the code below, showing how you reach your answer. [3]
total = 0
for i in range(n):
for j in range(10):
total = total + i * j
print(total)
4. ShelfWise holds 1,000,000 books. Compare the approximate worst-case number of comparisons for an O(n) search and an O(log n) search, and comment on scalability. [3]
5. Algorithm A reverses a list by swapping elements within it. Algorithm B builds a new reversed list. State and explain the space complexity of each. [2]
6. Discuss whether an O(n²) sorting algorithm is ever a suitable choice. [4]