AlgoViz

Time complexity compared

easy 18 min

The seven common time complexities in one place: 1 < log n < n < n log n < n² < 2ⁿ < n!.

Chapter mnemonic

Common growth rates in order

Tap, halve, walk, split and sweep, pair, pick subsets, permute.

Which grows faster as n increases: trying all pairs or choosing every subset?

Subsets. Quadratic pair growth is eventually overtaken by exponential subset growth.

Video lesson · Chapter 1 of 5

Compare work before comparing stopwatches

0:00 / 4:36

All seven complexities in 90 seconds

1:27Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Count the work. Find how many basic steps the algorithm takes as a function of the input size n

Understand it

Start here

Why compare growth rates?

Every algorithm has a growth rate: how its work changes as the input size nn grows. The gap between classes is not a few percent. At n=1,000,000n = 1{,}000{,}000, an O(n)O(n) loop does a million steps and an O(n2)O(n^2) nested loop does a trillion. At about 10810^8 simple steps per second, that is a hundredth of a second against almost three hours.

  • Interviews

    Almost every coding interview asks for the time complexity of your solution, and whether you can do better.

  • Real systems

    The growth rate decides whether an app stays fast or grinds to a halt as data piles up.

  • Scalability

    Good code works for 1,000 users and for 1 million. A quadratic step that is fine today can be the outage next year.

The ladder to remember

1  <  log⁡n  <  n  <  nlog⁡n  <  n2  <  2n  <  n!1 \;<\; \log n \;<\; n \;<\; n\log n \;<\; n^2 \;<\; 2^n \;<\; n!
From the flat line to the explosion. For large enough nn, each class does less work than every class to its right.

Definitions

Big O, Big Ω and Big Θ

Big O: an upper bound

f(n)=O(g(n))  ⟺  ∃ c>0, n0  :  0≤f(n)≤c⋅g(n)  for all n≥n0f(n) = O(g(n)) \iff \exists\, c > 0,\ n_0 \;:\; 0 \le f(n) \le c \cdot g(n) \ \text{ for all } n \ge n_0
From some point on, ff never grows faster than a constant multiple of gg. Saying merge sort is O(n2)O(n^2) is true but loose; O(nlog⁡n)O(n \log n) is the useful bound.

Big Ω: a lower bound

f(n)=Ω(g(n))  ⟺  ∃ c>0, n0  :  f(n)≥c⋅g(n)≥0  for all n≥n0f(n) = \Omega(g(n)) \iff \exists\, c > 0,\ n_0 \;:\; f(n) \ge c \cdot g(n) \ge 0 \ \text{ for all } n \ge n_0
From some point on, ff always does at least a constant multiple of gg. Any algorithm that must read all its input is Ω(n)\Omega(n).

Big Θ: a tight bound

f(n)=Θ(g(n))  ⟺  c1⋅g(n)≤f(n)≤c2⋅g(n)  for all n≥n0  ⟺  f=O(g) and f=Ω(g)f(n) = \Theta(g(n)) \iff c_1 \cdot g(n) \le f(n) \le c_2 \cdot g(n) \ \text{ for all } n \ge n_0 \iff f = O(g) \text{ and } f = \Omega(g)
ff is squeezed between two multiples of gg. When engineers say "this is O(n)O(n)" they usually mean Θ(n)\Theta(n): exactly linear, not just at most linear.

How the three bounds fit together

Big O caps the growth from above, Big Ω from below. When both hold for the same gg, the growth rate is pinned down exactly.

The ladder

The order of growth

Which one grows faster?

lim⁡n→∞f(n)g(n)=0  ⇒  f grows strictly slower than ge.g. nlog⁡nn2=log⁡nn→0\lim_{n \to \infty} \frac{f(n)}{g(n)} = 0 \;\Rightarrow\; f \text{ grows strictly slower than } g \qquad\text{e.g. } \frac{n \log n}{n^2} = \frac{\log n}{n} \to 0
Divide one cost by the other and let nn grow. If the ratio shrinks to 0 the top one is lower on the ladder. 2nn!→0\frac{2^n}{n!} \to 0 too, so factorial beats exponential.

From the flat line to the explosion

Each arrow points to a class that grows faster. Moving one rung up the ladder is usually the biggest speed-up you can get.

The seven classes

Meet each class

  • O(1)O(1) constant

    Same time for any nn. Array index, hash lookup, stack push. Like a light switch. Deep dive: Open

  • O(log⁡n)O(\log n) logarithmic

    Halves the problem each step. Binary search, balanced BST. Like finding a word in a dictionary. Deep dive: Open

  • O(n)O(n) linear

    One pass over the input. Linear search, finding the max. Like reading a book page by page. Deep dive: Open

  • O(nlog⁡n)O(n \log n) linearithmic

    Divide, then merge. Merge sort, heap sort. Like organising a library shelf. Deep dive: Open

  • O(n2)O(n^2) quadratic

    Every pair. Bubble sort, nested loops. Like handshakes at a party. Deep dive: Open

  • O(2n)O(2^n) exponential

    Two choices per item. All subsets, naive Fibonacci. Like a chain letter doubling. Deep dive: Open

  • O(n!)O(n!) factorial

    Every ordering. All permutations, brute-force travelling salesman. Like every seating plan. Deep dive: Open

Algorithms and code shapes

ClassClassic algorithmsCode shape
O(1)O(1)Array access by index, hash table lookup, stack push and popNo loop that depends on nn
O(log⁡n)O(\log n)Binary search, balanced BST operations, fast powerDivide the search space by 2 each round
O(n)O(n)Linear search, array traversal, finding the maxOne loop over all nn items
O(nlog⁡n)O(n \log n)Merge sort, heap sort, quicksort on averageDivide and conquer with a linear merge, or nn heap operations
O(n2)O(n^2)Bubble sort, selection sort, checking all pairsTwo nested loops over nn
O(2n)O(2^n)Naive recursive Fibonacci, power set, Tower of HanoiTwo recursive calls per item
O(n!)O(n!)All permutations, brute-force travelling salesman, brute-force N-QueensTry every ordering of the nn items

The numbers

The big comparison table

Classn = 10n = 100n = 1,000n = 10610^6
O(1)O(1)1111
O(log⁡n)O(\log n)3.36.61020
O(n)O(n)101001,00010610^6
O(nlog⁡n)O(n \log n)336649,9662×1072 \times 10^7
O(n2)O(n^2)10010,00010610^6101210^{12}
O(2n)O(2^n)1,0241.3×10301.3 \times 10^{30}1.1×103011.1 \times 10^{301}about 10301,03010^{301{,}030}
O(n!)O(n!)3,628,8009.3×101579.3 \times 10^{157}about 102,56810^{2{,}568}about 105,565,70910^{5{,}565{,}709}
Operation counts with log⁡2\log_2. The bottom two rows are finite numbers, but no computer could ever finish them.

Logs and powers of two to keep in your head

210≈103220≈106230≈109⟹log⁡2103≈10, log⁡2106≈20, log⁡2109≈302^{10} \approx 10^3 \qquad 2^{20} \approx 10^6 \qquad 2^{30} \approx 10^9 \quad\Longrightarrow\quad \log_2 10^3 \approx 10,\ \log_2 10^6 \approx 20,\ \log_2 10^9 \approx 30
These three anchors let you fill in most of the table by hand: nlog⁡nn \log n at a million is about 106×20=2×10710^6 \times 20 = 2 \times 10^7.

Time budget

What n can I afford in one second?

The one-second rule

f(n)≤108simple steps  ≈  1 secondf(n) \le 10^8 \quad\text{simple steps} \;\approx\; 1 \text{ second}
A rough rule for C++ or Java on a modern machine; Python is often 10 to 50 times slower per step. Solve f(n)≤108f(n) \le 10^8 for each class.
ClassLargest n in about 1 secondWhy
O(1)O(1)any nThe cost never grows
O(log⁡n)O(\log n)any practical nlog⁡21018≈60\log_2 10^{18} \approx 60
O(n)O(n)10810^8One step per item
O(nlog⁡n)O(n \log n)about 4.5 million4.5×106×22≈1084.5 \times 10^6 \times 22 \approx 10^8
O(n2)O(n^2)10,000104×104=10810^4 \times 10^4 = 10^8
O(n3)O(n^3)about 4604643≈108464^3 \approx 10^8
O(2n)O(2^n)26226≈6.7×1072^{26} \approx 6.7 \times 10^7
O(n!)O(n!)1111!≈4×10711! \approx 4 \times 10^7, but 12!≈4.8×10812! \approx 4.8 \times 10^8

The same classes as wall-clock time at n = 1,000,000

ClassStepsTime at 10810^8 per second
O(log⁡n)O(\log n)200.2 microseconds
O(n)O(n)10610^60.01 seconds
O(nlog⁡n)O(n \log n)2×1072 \times 10^70.2 seconds
O(n2)O(n^2)101210^{12}about 2.8 hours
O(2n)O(2^n)10301,03010^{301{,}030}never

Scaling

What happens when n doubles

ClassEffect of doubling n1 second at n becomes
O(1)O(1)No change1 second
O(log⁡n)O(\log n)One more stepa hair over 1 second
O(n)O(n)Twice the work2 seconds
O(nlog⁡n)O(n \log n)A bit more than twiceabout 2.1 seconds
O(n2)O(n^2)Four times the work4 seconds
O(2n)O(2^n)The work is squared2n2^n seconds
O(n!)O(n!)Multiplied by (n+1)(n+2)⋯(2n)(n+1)(n+2)\cdots(2n)astronomical

Where those factors come from

log⁡2(2n)=log⁡2n+1(2n)2=4n222n=(2n)22n+1=2⋅2n\log_2(2n) = \log_2 n + 1 \qquad (2n)^2 = 4n^2 \qquad 2^{2n} = \left(2^n\right)^2 \qquad 2^{n+1} = 2 \cdot 2^n
For exponential growth, adding one item already doubles the work, and doubling nn squares it.

Constraints

From the constraint to the target

n is at mostAim forTypical problems
10 to 11O(n!)O(n!) or O(2n)O(2^n)Permutations, N-Queens, Sudoku solver
20 to 25O(2n)O(2^n)Subsets, combination sum, partition problems
100 to 500O(n3)O(n^3)Floyd-Warshall, DP with three indices
1,000 to 10,000O(n2)O(n^2)All pairs, simple 2D DP
10510^5 to 10610^6O(nlog⁡n)O(n \log n) or O(n)O(n)Sorting, heaps, two pointers, sliding window
10810^8 and moreO(log⁡n)O(\log n) or O(1)O(1)Binary search, math formulas
Problem setters pick the limit so the intended solution fits in about a second. Read it before you design.

Pick a target from the largest n

Work down until a test passes. The answer is the slowest class you are allowed; anything faster is a bonus.

Spotting

Spot the class in code

Which class is this code?

Ask the questions from the most distinctive shape to the most common. Anything hidden inside a loop, such as in on a list, multiplies the cost.
Python
from itertools import permutationsdef first(arr):                  # O(1)    return arr[0]def halvings(n):                 # O(log n)    steps = 0    while n > 1:        n //= 2        steps += 1    return stepsdef total(arr):                  # O(n)    s = 0    for x in arr:        s += x    return sdef sort_it(arr):                # O(n log n)    return sorted(arr)def count_pairs(arr):            # O(n^2)    pairs = 0    for i in range(len(arr)):        for j in range(i + 1, len(arr)):            pairs += 1    return pairsdef count_subsets(arr):          # O(2^n): two calls per item    if not arr:        return 1    rest = arr[1:]    return count_subsets(rest) + count_subsets(rest)  # skip it, take itdef count_orders(arr):           # O(n!)    return sum(1 for _ in permutations(arr))data = [5, 3, 8, 1, 9, 2, 7, 4]print(first(data), halvings(len(data)), total(data))   # 5 3 39print(sort_it(data))print(count_pairs(data), count_subsets(data), count_orders(data))  # 28 256 40320
One small function per class, run on the same 8 items. The counts are 1, 3, 8, 8 sorted, 28 pairs, 256 subsets and 40,320 orderings.
Edit and run it in your browser

Simplifying

Dropping constants and smaller terms

From a step count to a class
  1. 1Count3n² + 5n + 2
  2. 2Drop constantsn² + n + 1
  3. 3Keep the biggest termn²
  4. 4Name the classO(n²)

For large $n$ the $n^2$ term dwarfs the rest: at $n = 1{,}000$ it is 3,000,000 of the 3,005,002 steps.

Proving 3n² + 5n + 2 is Θ(n²)

3n2  ≤  3n2+5n+2  ≤  4n2for all n≥6(c1=3, c2=4, n0=6)3n^2 \;\le\; 3n^2 + 5n + 2 \;\le\; 4n^2 \quad\text{for all } n \ge 6 \qquad (c_1 = 3,\ c_2 = 4,\ n_0 = 6)
The right side holds once n2≥5n+2n^2 \ge 5n + 2, which is true from n=6n = 6. Both bounds use n2n^2, so the cost is Θ(n2)\Theta(n^2).

Rules that hold

  • Loops one after another add: O(n)+O(m)=O(n+m)O(n) + O(m) = O(n + m).
  • Nested loops multiply: O(n)×O(m)=O(nm)O(n) \times O(m) = O(nm).
  • The base of a log does not matter: log⁡2n\log_2 n and log⁡10n\log_{10} n differ by a constant.
  • Keep separate inputs separate: a loop over nn and one over mm is not O(n)O(n).

Rules that do not

  • The base of an exponential matters: 3n=1.5n⋅2n3^n = 1.5^n \cdot 2^n, so O(3n)≠O(2n)O(3^n) \ne O(2^n).
  • An exponent on nn matters: O(n2)O(n^2) is not O(n)O(n).
  • A single loop is not always O(n)O(n): hidden work inside multiplies it.
  • Big O alone does not say which case: best, average and worst can differ.

Judgement

When the bigger Big O wins

  • Small inputs

    For 100n100n against n2n^2, the quadratic is faster until n=100n = 100. Python's sort uses insertion sort on short runs for exactly this reason.

  • Constants and memory

    Two O(n)O(n) loops can differ by 10 times because of cache misses, allocation or the language. Big O hides these.

  • Average vs worst

    Quicksort is O(nlog⁡n)O(n \log n) on average but O(n2)O(n^2) in the worst case; hash maps are O(1)O(1) on average but O(n)O(n) when everything collides.

  • Amortised cost

    A dynamic array append is occasionally O(n)O(n) when it resizes, but O(1)O(1) averaged over many appends.

Where a slower class overtakes a faster one

100 n≤n2  ⟺  n≥1001000 nlog⁡2n≤n2  ⟺  n≳14,000100\,n \le n^2 \iff n \ge 100 \qquad\qquad 1000\,n\log_2 n \le n^2 \iff n \gtrsim 14{,}000
The class with the better growth always wins eventually; constant factors only decide where the crossover is.

Recap

Key takeaways

Key points

  • The ladder: 1<log⁡n<n<nlog⁡n<n2<2n<n!1 < \log n < n < n\log n < n^2 < 2^n < n!, from the flat line to the explosion.
  • Big O is an upper bound, Big Ω a lower bound, Big Θ both at once.
  • At n=106n = 10^6: 1, 20, 10610^6, 2×1072 \times 10^7, 101210^{12}, and two counts that can never finish.
  • In about a second (10810^8 steps): O(n)O(n) to 10810^8, O(nlog⁡n)O(n \log n) to about 4.5 million, O(n2)O(n^2) to 10410^4, O(2n)O(2^n) to 26, O(n!)O(n!) to 11.
  • Read the constraint first: it tells you the class the intended solution belongs to.
  • Drop constants and smaller terms, add sequential loops, multiply nested ones, and watch for hidden work.
  • Each class has its own deep dive: Open, Open, Open, Open, Open, Open, Open.

Sources