Beginner 12 min

Big O and growth

Count work and explain how it grows when you give an algorithm more input.

Count meaningful work

Start by choosing the input size, usually the number of items. Pick an operation that captures the growing work. Summing n items performs n additions, so the running time grows linearly. Checking the first item takes a fixed number of operations regardless of list length.

How it works

Compare what happens when the input doubles. A single pass might read twice as many items. A loop that pairs every item with every other item may do about four times as much work. This comparison is useful even if the two versions have different constant costs.

Separate time from extra space

A sum takes O(n) time but uses O(1) additional space, because its running total and index do not grow with n. Building a separate list of all n items requires O(n) additional space. These bounds describe growth and leave out constant factors.

Code example

values = [4, 7, 9]
total, additions = 0, 0
for value in values:
    total += value
    additions += 1
print(total, additions)

Check your understanding

Two independent loops each visit every item in a list. Count the total visits and give the time bound.

See the example and explanation
Example 1
Given n = 4
Answer 8 visits, O(n)
Example 2
Given n = 100
Answer 200 visits, O(n)

The total is 2n. As the input grows the operation count remains proportional to n, so the tight growth bound is linear and the time is O(n).

Open practice problem
Next lessonLinear search