Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Algorithm complexity

By the end of this chapter, you'll be able to

  • Count an algorithm's operations as a function of the data size
  • Express a complexity with Big O notation
  • Compare linear search and binary search
  • Spot a hidden quadratic complexity and fix it

Count rather than time

Measured time depends on the machine, its load, the language. To compare algorithms, we count the elementary operations as a function of the size n of the data. Take searching for an item in a list, looking at each cell until it is found:

def linear_search(items, target):
    comparisons = 0
    for i, value in enumerate(items):
        comparisons += 1
        if value == target:
            return i, comparisons
    return -1, comparisons

for n in (10, 1_000, 1_000_000):
    data = list(range(n))
    print(n, linear_search(data, n - 1)[1], "comparisons")
10 10 comparisons
1000 1000 comparisons
1000000 1000000 comparisons

In the worst case (the item is at the end, or missing), the number of comparisons equals n: multiplying the data by 1,000 multiplies the work by 1,000. Linear search is said to be O(n) (“big O of n”).

Big O notation

Big O notation describes the order of magnitude of the growth, ignoring constants and terms that become negligible for large values of n:

ComplexityNamen = 1,000n = 1,000,000Example
O(1)constant11read items[i], look up a key in a dictionary
O(log n)logarithmic~10~20binary search
O(n)linear1,0001,000,000go through a list
O(n log n)linearithmic~10,000~20,000,000good sorting algorithms
O(n²)quadratic1,000,00010¹²two nested loops over the data

The columns give the order of magnitude of the number of operations. A million operations take a fraction of a second; 10¹² would take hours.

Binary search

If the list is sorted, you can do much better: look at the middle, and discard at once the half that cannot contain the target. This is binary search, as when you look up a word in a paper dictionary.

def binary_search(items, target):
    start, end, comparisons = 0, len(items) - 1, 0
    while start <= end:
        middle = (start + end) // 2
        comparisons += 1
        if items[middle] == target:
            return middle, comparisons
        if items[middle] < target:
            start = middle + 1
        else:
            end = middle - 1
    return -1, comparisons

for n in (10, 1_000, 1_000_000):
    data = list(range(n))
    print(n, binary_search(data, n - 1)[1], "comparisons")
10 4 comparisons
1000 10 comparisons
1000000 20 comparisons

At each step, the search area is halved: it takes about log₂(n) steps, around twenty for a million items instead of a million. This is O(log n). The price to pay: the list must be sorted.

Found in 3 comparisons, instead of 5 by going through the list.

Step 6 of 6
Text description of the animation
  1. We look for 23 in the 8 cells.
  2. The middle is cell 3, which holds 17.
  3. 17 is too small: 23 can only be on the right. Cells 0 to 3 are discarded.
  4. New middle: cell 5, which holds 31.
  5. 31 is too large: only cell 4 is kept.
  6. Found in 3 comparisons, instead of 5 by going through the list.

Mini-lab: make n growPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the first occurrence

A sorted list can contain duplicates: [2, 5, 5, 5, 8, 13]. Adapt binary search so that it returns the position of the first occurrence of the target (1 for 5), or -1 if it is missing, still in O(log n).

Hint 1
When you find the target, do not stop: note the position, then keep searching on the left.
Hint 2
In that case, set end = middle - 1 and keep the last position found in a result variable.
Show the solution and common mistakes
def first_occurrence(items, target):
    start, end, result = 0, len(items) - 1, -1
    while start <= end:
        middle = (start + end) // 2
        if items[middle] == target:
            result = middle
            end = middle - 1
        elif items[middle] < target:
            start = middle + 1
        else:
            end = middle - 1
    return result

data = [2, 5, 5, 5, 8, 13]
print(first_occurrence(data, 5), first_occurrence(data, 13), first_occurrence(data, 7))
1 5 -1

The search area keeps being halved at each step: the complexity stays O(log n), even with many duplicates. Python's bisect module provides this search ready-made: bisect.bisect_left(items, target).

Common mistakes:

  • Finding an occurrence, then moving back cell by cell to the first one: on a list of a million 5s, you are back to O(n).
  • Writing while start < end: you forget the last possible cell, and a target located there is never found.

Summary

  1. 1Complexity describes how the number of operations grows with the data size n.
  2. 2Big O notation keeps the order of magnitude: O(1), O(log n), O(n), O(n log n), O(n²).
  3. 3Binary search halves the area at each step: O(log n), on a sorted list.
  4. 4x in a_list costs O(n); x in a_set costs O(1) on average, thanks to hashing.
  5. 5Two nested loops over the data often signal an O(n²) to remove.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.