Time complexity: how much slower when the data grows (Big O)

Your code was fast with 10 items and seems stuck with a million. The reason is the answer to one question: when the data doubles, how many times more steps does it take? Move n to compare six growth shapes, then count the steps of finding a value yourself.

Short answer. Time complexity is the shape of how the number of steps grows as the data size n grows. It is not seconds. You write it in Big O (O(…)) and drop constants and small terms. O(n) means double n, double the steps. O(n²) means four times. O(log n) means just one more step. So once n is large, the shape matters more than how fast the machine is.

ShapeWhen n doublesExampleSteps at this n
O(1)sameread the k-th item of a list
O(log n)one more stepcut sorted cells in half to find a value
O(n)doublelook one by one from the front
O(n log n)a bit more than doublesorting
O(n²)four timescompare every pair (a for inside a for)
O(2ⁿ)double when n grows by just onetry every subset

Reading the chart: across runs from 1 to 2n. The dashed vertical line is the current n, and the numbers to its left are the steps at n. A bent arrow is n doubling to 2n; ×2 and ×4 on the arrow mean how many times, +1 means how many more. Curve names sit at the right end next to their color, and curves that leave through the top are marked with "↑" where they leave.

Change n with the slider or the number box (2 to 1000). The steps are the formula with n put in, rounded to 0.1 (log₂n is not a whole number unless n is a power of 2). From n = 53, 2ⁿ shows as "too many to count". Past that, the numbers on this page can no longer hold the exact whole number.

Try this. ① At the start, n = 8, the steps are 1, 3, 8, 24, 64, 256. The chart runs to 2n = 16. At the dashed line (n = 8), 2ⁿ has already left through the top, and n² is still inside at 64 but leaves before reaching 16. The arrow labels are ×1 for 1, +1 for log₂n, ×2 for n and ×2.7 for n·log₂n; n² and 2ⁿ, which leave the top, show ×4 and ×256. ② Double n to 16 and you get 4, 16, 64, 256, 65,536. log₂n grows by one (3 → 4), n doubles, n² is four times (64 → 256), and 2ⁿ is squared (256 → 65,536). ③ At n = 52, 2ⁿ is 4,503,599,627,370,496. From 53 on it is too many to count. ④ At n = 1000, log₂n is 10, n is 1,000, n·log₂n is 9,965.8 and n² is 1,000,000. In the chart, 1 and log₂n lie on the floor, and even n sinks close to it.

Definitions

The sections below explain with plain words about counting steps. The textbook definitions are these. n is the input size (the number of items), and f(n), g(n) are functions that take values of 0 or more for natural numbers n.

time complexity
The number of basic operations an algorithm performs, written as a function T(n) of the input size n. A basic operation finishes in constant time no matter what n is, like reading one cell or comparing two values.
Big O notation
If there are a positive constant c and a natural number n₀ such that f(n) ≤ c·g(n) for every n ≥ n₀, you write f(n) = O(g(n)). Then g(n) is an asymptotic upper bound of f(n).

f(n)=O(g(n))⟺∃c>0, n0: f(n)≤cg(n) (n≥n0)

tilde approximation
If f(n) divided by g(n) goes to 1 as n grows without bound, you write f(n) ~ g(n). Unlike Big O, it keeps the constant of the largest term.

f(n)~g(n)⟺limn→∞f(n)g(n)=1

worst case, average case, best case
When the operation count T(x) differs for each input x of size n, the worst case is the largest of them, the best case is the smallest, and the average case is the average weighted by the probability P(x) of each input (the expected value). The average case is only fixed once you assume a distribution of inputs.

Tworst(n)=max|x|=nT(x)

Tavg(n)=∑|x|=nP(x)T(x)

Tbest(n)=min|x|=nT(x)

space complexity
The amount of memory an algorithm uses, written as a function of the input size n. This page counts only the extra memory, not the cells that hold the input. It uses the same asymptotic notation as time complexity.
amortized analysis
An analysis that takes the worst-case total cost T(m) of m operations in a row, divides it by m, and uses that as the cost of one operation. It uses no probability, so it is different from the average case. It is a worst-case promise for the whole run of operations.

1. What Big O measures: the shape of growth, not seconds

Running time is roughly time per step × number of steps. The machine, the language and the cache decide the first part. The algorithm and the data size n decide the second. Time complexity looks only at the second part. A step is one small job that finishes at once, like reading one cell or comparing two values.

So Big O does not talk about seconds. It says "when n doubles, how many times more steps". On a computer ten times faster, O(n²) code still takes four times longer when n doubles. Once n is big enough, a worse shape cannot be saved by a faster machine. In the experiment above, at n = 1000, n² is 1,000 times n.

The textbook definition: if, for large enough n, f(n) never goes above some constant times g(n), you write f(n) = O(g(n)). So Big O is an upper bound: "it grows no faster than this". Usually you write the tightest shape that fits.

2. Count the steps: two ways to find a value

Take n cells sorted from small to large (2, 4, 6, …, 2n) and find one value. One by one from the front looks at the cells in order from the first. Cutting in half looks at the middle cell of the range that is left. If that value is smaller than the target, it throws away the left half; if larger, the right half. The cells are sorted, so the target cannot be in the half thrown away. The experiment below runs both methods and counts one step for each cell looked at.

When cells are wide, the values are written inside and the order of looking (1, 2, 3, …) is written under the bottom strip. When cells get narrow, only the looked-at cells are painted. "missing value" is the odd number one more than the last value.

Try this. ① At the start (8 cells, last value 16) one by one takes 8 steps and cutting in half takes 4. Cutting in half looks at 8, 12, 14, 16 (the table in section 3). ② "first value" takes 1 step one by one and 3 steps cutting in half. "middle value" (8) takes 4 steps one by one and 1 step cutting in half. The best case is different for each method. ③ Set n to 500 and find the last value: 500 steps and 9 steps. Double it to 1000: 1,000 steps and 10 steps. One by one doubles; cutting in half adds one step. ④ "missing value" takes as many steps as the last value for both methods. You only know it is missing when there is nowhere left to look.

3. Follow it by hand: find 16 in 8 cells

This is the same input as the start of experiment ②. The cells are 2, 4, 6, 8, 10, 12, 14, 16, numbered 0 to 7. We look for 16.

One by one from the front. It looks at 2, 4, 6, 8, 10, 12, 14, none of them match, and meets 16 at the eighth cell. 8 steps. The value is last, so it costs as many steps as there are cells.

Cutting in half. The middle cell number is (left end + right end) ÷ 2, rounded down.

StepRange left (cell numbers)Middle cellIts valueCompared with 16Next
10 to 7 (8 cells)38smaller (8 < 16). The cells are sorted, so 16 can only be to the rightdrop 0 to 3 → 4 to 7
24 to 7 (4 cells)512smaller (12 < 16). 16 can only be to the rightdrop 4 to 5 → 6 to 7
36 to 7 (2 cells)614smaller (14 < 16). 16 can only be to the rightdrop 6 → 7 to 7
47 to 7 (1 cell)716equal (16 = 16)found
step 1 2 4 6 8 10 12 14 16 ▼ 8 cells 8 < 16 ÷2 step 2 2 4 6 8 10 12 14 16 ▼ 4 cells 12 < 16 ÷2 step 3 2 4 6 8 10 12 14 16 ▼ 2 cells 14 < 16 ÷2 step 4 2 4 6 8 10 12 14 16 ▼ 1 cell 16 = 16 found
The cells left halve: 8 → 4 → 2 → 1. Each step looks at the middle cell (blue, ▼) of the range left (bracket below) and compares it with 16. When 16 is bigger, everything up to the middle is dropped (faded cells). The fourth step finds it in the cell with the orange outline.

The cells left went 8 → 4 → 2 → 1, halving each time. The number of halvings from 8 down to 1 is log₂8 = 3, plus one step to look at the last cell, so 4 steps. In general it takes at most ⌊log₂n⌋ + 1 steps (⌊ ⌋ means round down). For n = 1000 that is 10 steps. Doubling the cells adds only one more halving, which is why it is O(log n). The binary search page goes deeper.

4. The rules: drop constants and small terms

RuleExampleWhy
Drop constant factors3n → O(n)Constants change with the machine and the language. How many times more steps you get when n doubles does not depend on them
Drop small termsn² + 100n → O(n²)At n = 1,000, n² is 1,000,000 and 100n is 100,000. At n = 100,000 it is 10,000,000,000 against 10,000,000, so the small term is 0.1%. The bigger n gets, the more only the big term matters
One after another: keep the biggersort (n log n), then one pass (n) → O(n log n)Add the two and the smaller one becomes a small term
One inside another: multiplya for over n inside a for over n → O(n²)Each turn of the outer loop runs n inner steps
Do not write the log baselog₂n and log₁₀n are both O(log n)Changing the base only changes a constant factor (log₂n ≈ 3.32 × log₁₀n)
n = 4 4 × 4 = 16 cells n doubles cells ×4 inner for: 8 steps per row outer for: 8 rows n = 8 8 × 8 = 64 cells
Double n and the cells go four times (16 → 64). This draws "nested loops multiply" as cells. One row is the n steps of the inner for, and the number of rows is the n rounds of the outer for. Both double, so 2 × 2 = 4 times. It is the same 64 that n² shows at n = 8 in experiment ①.

There is one reason behind all of these. Big O is a tool for seeing what wins as n grows, so it does not carry around things that get buried anyway when n grows. The flip side is that for small n, what was dropped can still be large (question 1 below). Princeton's algorithms textbook uses a tilde notation that drops only the small terms and keeps the leading constant: 3n² + 100n ~ 3n². Big O goes one step further and drops the 3 as well.

5. Worst case and average case

Even with the same n, the steps depend on the input. As experiment ② showed, depending on where the value is, it can take 1 step or n steps. So you say which case you mean.

6. Memory is measured the same way

Memory is measured as how the extra cells, beyond the input, grow with n (space complexity). The rules are the same as for time.

You can trade memory for time. If you need to look up values in a list many times, build a set or a dict once. It costs n more cells, but each lookup drops from O(n) to O(1) on average. When the Princeton textbook counts memory in bytes, it multiplies the number of variables by the bytes their type uses and adds them up (for Java).

7. Steps of common operations: when to use what

These are the values in the Python docs (for CPython). The plain words are the same as in the table of experiment ①: O(1) does not depend on n, O(log n) is one more step when n doubles, O(n) doubles when n doubles.

JobPythonBestAverageWorstExtra memoryWhen to use
Add to the end of a lista.append(x)O(1)O(1)O(n) for that one call (when the list grows and moves), O(1) amortizednoneAlways, for building a list up
Add to the front of a lista.insert(0, x)O(n)O(n)O(n)noneEvery later item moves one cell. If you often add or remove at both ends, use collections.deque
Is a value in a listx in aO(1)O(n)O(n)noneFine once or twice. If you ask inside a loop, use a set or a dict
Cut sorted cells in half to findbisect.bisect_left(a, x)O(log n)O(log n)O(log n)noneWhen the data is already sorted and you also need the order
Look up in a dictd[k], k in dO(1)O(1)O(n) (when every key has the same hash)the dict itself, n cellsWhen you look things up by key many times
Sortsorted(a), a.sort()O(n) (comparisons when already sorted or reversed)O(n log n)O(n log n)sorted makes a new list, n cellsSort once, then search many times. Methods: elementary sorts, merge and quick sort

The cutting-in-half search in experiment ② stops after 1 step on the middle value, but bisect_left does not stop on an equal value. It keeps narrowing down to the insertion point, so it always takes about log n steps. Why a dict is O(1) on average is on the hash table page.

8. In Python

The cutting-in-half search from experiment ②, counting steps.

def binary_search(cells, target):          # cells are sorted from small to large
    low, high, steps = 0, len(cells) - 1, 0
    while low <= high:
        middle = (low + high) // 2           # the middle cell of the range left
        steps += 1
        if cells[middle] == target:
            return middle, steps
        if cells[middle] < target:
            low = middle + 1                 # drop the left half
        else:
            high = middle - 1                # drop the right half
    return -1, steps

cells = list(range(2, 2001, 2))              # 2, 4, ..., 2000 (1000 cells)
print(binary_search(cells, 2000))            # (999, 10)
import bisect; print(bisect.bisect_left(cells, 2000))  # 999: the standard library

Where it is used

Frequently asked

Is the smaller Big O always faster?

No. Big O only describes how the steps grow when n is large. The constants and small terms it drops can be big when n is small. With only a few cells, a simple O(n²) method can beat an O(n log n) one. If you care about real time, measure it while doubling n.

Why is a dict lookup O(1) but O(n) in the worst case?

The dict times in the Python docs are average times that assume hash values rarely collide. Then a lookup takes a few steps no matter how many keys there are. In the worst case every key has the same hash, the colliding keys must be compared one by one, and it becomes O(n).

append sometimes moves everything, so why is it O(1)?

When a list runs out of room, it moves everything to a bigger space. That one call is O(n), but it happens rarely, so the total cost of many appends divided by the number of appends is O(1) each. This is called amortized cost. Keep it in mind where every single call must be fast.

Words

Plain words hereTextbook term
how the steps grow with ntime complexity, order of growth
Big O, upper boundBig O notation, asymptotic notation
how extra memory growsspace complexity
same · one more step · double · a bit more than double · four times · double per extra itemconstant · logarithmic · linear · linearithmic · quadratic · exponential
worst · average · bestworst case · average case · best case
spreading the costamortized analysis
dropping only the small termstilde approximation (~)
one by one from the front · cutting in halflinear search · binary search

Sources

← AI agentsElementary sorts →