Skip to content
duc zk

Big-O notation

Counting steps instead of seconds, and what the common growth rates feel like.

Updated

On this page

Seconds depend on the machine. Steps do not. Big-O describes how the number of steps grows as the input size n grows, ignoring constant factors.

The common growth rates

NotationNameExample
O(1)constantread an array element
O(log n)logarithmicbinary search
O(n)linearscan a list
O(n log n)linearithmicmerge sort
O(n²)quadraticcompare every pair

Drag the slider to see how far apart the rates drift as n grows:

O(1) 1
O(log n) 4
O(n) 16
O(n²) 256

Steps for one run. Bars use a log scale so all four stay visible.

Reading code for its growth rate

def has_duplicate(items):
    for i, a in enumerate(items):
        for b in items[i + 1:]:
            if a == b:
                return True
    return False

Two nested loops over the same input: O(n²). A set brings it down to O(n) at the cost of O(n) extra memory.

What gets dropped

Constants and lower-order terms: 3n² + 10n + 7 is O(n²). They still matter for small n.

Worst, average, amortised

  • Worst case: the upper bound for any input of size n.
  • Average case: expected cost over a distribution of inputs.
  • Amortised: average cost per operation over a sequence, such as appending to a dynamic array.