Home › Theme B › B2 › B2.4 › B2.4.1

B2.4.1 Big O: how efficient is an algorithm?

SL + HLCommand terms: Describe, Calculate

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

Function:

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.

Chart up to n = 20  
Estimate for n = 1,000 books

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.

Snippet:
Its Big O is
Choose a snippet.

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.

Books n =   Limit:

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: simplify T(n)

Drop the constants and lower-order terms. What is the Big O?

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 4, task 1. Sprint 4 makes ShelfWise fast for big libraries. Before choosing algorithms, measure: count the steps three functions take as the catalogue doubles, and decide their Big O from the evidence.

Expected output

n count_overdue has_duplicate halvings 250 250 31125 7 500 500 124750 8 1000 1000 499500 9 2000 2000 1999000 10

Your analysis

Check my code

    Extension: time each function with 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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

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

    File: b2_4_1_average.py
    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
    How does the count change when n is multiplied by 10?
    Model solution

    Counts 100, 10 000, 1 000 000: multiplying n by 10 multiplies the work by 100, so it is O(n²).

    File: b2_4_1_average_solution.py
    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))
    
    Moderate

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

    File: b2_4_1_moderate.py
    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
    The inner loop starts at i + 1 so each pair is compared once.
    Model solution

    For n items with no duplicate, the slow version makes n(n − 1)/2 comparisons: 499 500 for n = 1 000.

    File: b2_4_1_moderate_solution.py
    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")
    
    Challenging

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

    File: b2_4_1_challenging.py
    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
    Repeat each timing a few times and keep the smallest, to reduce noise.
    Model solution
    File: b2_4_1_challenging_solution.py
    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:

    1. 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.
    2. 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.
    3. Identify and order the common classes O(1), O(log n), O(n), O(n log n), O(n²) and O(2ⁿ).
    4. Distinguish between time complexity and space complexity, and determine the space complexity of simple algorithms.
    5. 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

    1. Choose n: the size of the input (number of books, length of the list).
    2. 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.
    3. 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 ONamen doubles, work...Example
    O(1)Constantstays the sameRead books[5]; push onto a stack
    O(log n)Logarithmicincreases by one stepBinary search; halving loop
    O(n)LineardoublesLinear search; total of a list
    O(n log n)Linearithmicslightly more than doublesMerge sort, quicksort (average)
    O(n²)QuadraticquadruplesBubble and selection sort; comparing every pair
    O(2ⁿ)Exponentialsquares (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]

    It describes how the running time / number of operations (or memory) grows as the size of the input n grows [1]; giving an upper bound / worst case, ignoring constant factors and lower-order terms [1].

    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")
    (a) O(1) [1]; (b) O(n) [1]; (c) O(n²) [1].

    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)
    The inner loop runs a fixed 10 times for each of the n outer passes [1], so T(n) is about 10n + 2 operations [1]; constants are dropped, giving O(n) (not O(n²), because the inner loop does not depend on n) [1].

    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]

    O(n): about 1,000,000 comparisons [1]; O(log n): about log₂ 1,000,000 ≈ 20 comparisons [1]; if the catalogue doubles, the O(n) search doubles its work while the O(log n) search needs just one more comparison, so it scales far better [1].

    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]

    A: O(1) extra space, only a few variables are needed whatever n is [1]; B: O(n), a second list of n elements is created [1].

    6. Discuss whether an O(n²) sorting algorithm is ever a suitable choice. [4]

    For large n, an O(n²) algorithm scales badly: doubling n quadruples the time, so an O(n log n) algorithm is preferred [1]. For small n (e.g. a class list of 30) the difference is negligible [1], and a simple algorithm is easier to write, test and maintain / may have lower overhead [1]. It may also suit nearly sorted data or tight memory limits, e.g. bubble sort with an early exit / in-place O(1) space [1].