Skip to content
Tactiverge

Algorithms and complexity

What makes a method an algorithm, how to count the steps it takes, and how big-O notation predicts whether it will still be fast when the problem grows.

Lesson 1 of 6 · 30 min · Self-paced · Free

Why speed is a design requirement

A robot's planner might have 50 milliseconds to decide where to move next. A test on a small map runs instantly, so everything seems fine. Then the map grows ten times larger and the planner takes not ten times longer but a hundred — and the robot stutters, or stops. Engineers need a way to predict, before this happens, how the work a method does grows with the size of its input. That is what this lesson is about.

What is an algorithm?

An algorithm is a precise, finite sequence of steps that turns an input into an output. "Find the hottest reading" becomes an algorithm when it is written so carefully that anyone (or any computer) following it gets the same answer:

  1. Take the first reading as the best so far.
  2. For each remaining reading, compare it with the best so far; if it is larger, it becomes the new best.
  3. When no readings are left, the best so far is the answer.

In Python, with a counter for the comparisons:

def largest(values):
    best = values[0]
    comparisons = 0
    for v in values[1:]:
        comparisons += 1
        if v > best:
            best = v
    return best, comparisons

print(largest([3.2, 7.9, 1.4, 7.1, 5.5]))

Output:

(7.9, 4)

Five readings needed four comparisons. A thousand readings would need 999. In general, for n readings the algorithm does n − 1 comparisons: the work grows in proportion to n.

Counting steps instead of timing

Why count steps rather than time the program with a stopwatch? Times depend on the computer, on what else is running and on the language. Step counts depend only on the algorithm and the input, so they let you compare methods fairly and predict what will happen on bigger inputs.

Now a harder problem. A simulation has n obstacles and must check every pair for a collision. The first obstacle is checked against all the others, the second against those after it, and so on:

def count_pair_checks(n):
    checks = 0
    for i in range(n):
        for j in range(i + 1, n):
            checks += 1
    return checks

for n in [10, 100, 1000]:
    print(f"{n:5d} obstacles: {count_pair_checks(n):7d} checks")

Output:

   10 obstacles:      45 checks
  100 obstacles:    4950 checks
 1000 obstacles:  499500 checks

The exact formula is n(n − 1)/2. Each time n grows ten times, the work grows roughly a hundred times. A loop inside a loop is the classic sign of this behaviour.

Big-O notation

Big-O notation describes how the number of steps grows as the input size n becomes large, ignoring constant factors and smaller terms. The largest-reading algorithm does n − 1 steps: it is O(n), "order n", or linear. The pair check does n(n − 1)/2 = ½n² − ½n steps. For large n the n² term dominates and the ½ is just a constant, so it is O(n²), quadratic.

The common growth rates, from best to worst:

  • O(1), constant: the same work whatever n is, such as reading values[0].
  • O(log n), logarithmic: the work grows by one step each time n doubles. Binary search, in the next lesson, is like this.
  • O(n), linear: one pass through the data.
  • O(n log n): good sorting algorithms.
  • O(n²), quadratic: comparing every item with every other item.
  • O(2ⁿ), exponential: trying every subset of n items. Adding a single item doubles the work.

Numbers make the difference vivid:

import math

print(f"{'n':>9} {'log2 n':>7} {'n log2 n':>12} {'n²':>15}")
for n in [10, 1000, 1_000_000]:
    print(f"{n:>9} {math.log2(n):>7.1f} {n * math.log2(n):>12.0f} {n * n:>15}")

Output:

        n  log2 n     n log2 n              n²
       10     3.3           33             100
     1000    10.0         9966         1000000
  1000000    19.9     19931569   1000000000000

Suppose a computer does about 100 million simple steps per second (a rough figure; real speeds vary a lot). For a million items, an O(n log n) method needs about 20 million steps — a fraction of a second. An O(n²) method needs a million million steps — around three hours. An O(2ⁿ) method with n = 100 needs about 1.3 × 10³⁰ steps, which would keep that computer busy for roughly 400 million million years, tens of thousands of times the age of the universe.

Same problem, different algorithm

Big-O matters most when it helps you choose between methods. Every sensor on a robot's bus must have a unique ID. Here are two ways to check a list of IDs for duplicates:

def has_duplicate_pairs(ids):
    """Compare every pair: O(n²)."""
    steps = 0
    for i in range(len(ids)):
        for j in range(i + 1, len(ids)):
            steps += 1
            if ids[i] == ids[j]:
                return True, steps
    return False, steps

def has_duplicate_set(ids):
    """Remember what we have seen in a set: O(n)."""
    seen = set()
    steps = 0
    for x in ids:
        steps += 1
        if x in seen:
            return True, steps
        seen.add(x)
    return False, steps

ids = list(range(2000))      # 2000 different IDs: the worst case
print(has_duplicate_pairs(ids))
print(has_duplicate_set(ids))

Output:

(False, 1999000)
(False, 2000)

A set is a Python collection that stores each value once and can answer "is x in here?" in roughly constant time, however large it is. Using it turns nearly two million steps into two thousand. Same answer, a thousand times less work, and the gap widens as n grows.

Notice that we tested the worst case: a list with no duplicates, so neither function can stop early. When engineers quote a big-O figure, they usually mean the worst case, because that is the one that makes a robot miss its deadline.

What big-O does not tell you

Big-O is a guide, not the whole story:

  • It ignores constant factors. An O(n) method that does 1,000 operations per item can be slower than an O(n²) method for small n.
  • For small inputs, the simplest code is often the best choice. Optimise only where it matters.
  • It counts time, not memory. The set version uses extra memory to save time — a common trade-off.

When speed really matters, measure as well: Python's time.perf_counter() returns a precise clock reading, so the difference between two readings taken before and after a function call tells you how long it took. Run it several times, because individual timings vary.

Recap

  • An algorithm is a precise, finite set of steps from input to output.
  • Counting steps lets you compare algorithms independently of the computer.
  • Big-O describes growth for large n, ignoring constants: O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ).
  • A loop inside a loop over the same data often means O(n²).
  • A better algorithm or data structure, such as a set, can beat a faster computer by a huge margin.
  • Use big-O to choose, then measure to confirm.

Knowledge check

Check your understanding

  1. 1. An algorithm does 3n + 20 steps for an input of size n. What is its big-O?
  2. 2. An O(n²) method takes 2 seconds for 1,000 items. Roughly how long for 10,000 items?
  3. 3. Why do engineers usually quote the worst case?
  4. 4. Which change made the duplicate-ID check so much faster?
  5. 5. For an O(log n) algorithm, what happens to the work when n doubles?

Project

Programming project: measure growth

Investigate how step counts grow, using Python and a sheet of graph paper (or a free spreadsheet).

  1. Use count_pair_checks from this lesson for n = 10, 20, 40, 80, 160 and record the results. Each time n doubles, what happens to the count?
  2. Write a function that counts the steps to sum a list of n numbers, and record it for the same values of n.
  3. Plot both on the same axes. Describe the shapes in a sentence each.
  4. Use time.perf_counter() to time has_duplicate_pairs and has_duplicate_set on worst-case lists of 1,000, 2,000 and 4,000 IDs. Repeat each timing three times and note how much it varies. Do the timings grow the way the step counts predict?

No hardware is required.

Deliverables

  • A table of step counts for both functions and a hand-drawn or spreadsheet plot
  • Timings for the two duplicate checks, with repeats
  • A paragraph comparing your measurements with the big-O predictions

Go further

Algorithms and complexity — Computational Engineering — Tactiverge