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
Price eight records and sixteen
A nested-looking rescue procedure
Test a crossover prediction
Choose a plan for the drill
0:00 / 4:36
All seven complexities in 90 seconds
1:27·Reel
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
Keep the dominant term. Drop constant factors and smaller terms: 3n² + 5n + 2 becomes O(n²)
Place it on the ladder. Compare with 1 < log n < n < n log n < n² < 2ⁿ < n! and check what n fits in about a second
Understand it
Start here
Why compare growth rates?
Every algorithm has a growth rate: how its work changes as the input size n grows. The gap between classes is not a few percent. At n=1,000,000, an O(n) loop does a million steps and an O(n2) nested loop does a trillion. At about 108 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<logn<n<nlogn<n2<2n<n!
From the flat line to the explosion. For large enough n, 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≥n0
From some point on, f never grows faster than a constant multiple of g. Saying merge sort is O(n2) is true but loose; O(nlogn) is the useful bound.
Big Ω: a lower bound
f(n)=Ω(g(n))⟺∃c>0,n0:f(n)≥c⋅g(n)≥0 for all n≥n0
From some point on, f always does at least a constant multiple of g. Any algorithm that must read all its input is Ω(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 is squeezed between two multiples of g. When engineers say "this is O(n)" they usually mean Θ(n): exactly linear, not just at most linear.
How the three bounds fit together
flowchart TD
F["f(n), the real step count"] --> UP{"f(n) <= c * g(n) for all large n?"}
F --> LO{"f(n) >= c * g(n) for all large n?"}
UP -- yes --> O["f = O(g): upper bound"]
LO -- yes --> W["f = Ω(g): lower bound"]
O --> T["Both hold: f = Θ(g), a tight bound"]
W --> T
Big O caps the growth from above, Big Ω from below. When both hold for the same g, the growth rate is pinned down exactly.
The ladder
The order of growth
Which one grows faster?
n→∞limg(n)f(n)=0⇒f grows strictly slower than ge.g. n2nlogn=nlogn→0
Divide one cost by the other and let n grow. If the ratio shrinks to 0 the top one is lower on the ladder. n!2n→0 too, so factorial beats exponential.
From the flat line to the explosion
flowchart TD
A["O(1) constant: the flat line"] --> B["O(log n) logarithmic: the gentle curve"]
B --> C["O(n) linear: the diagonal"]
C --> D["O(n log n) linearithmic: the efficient sort"]
D --> E["O(n^2) quadratic: the steep climb"]
E --> F["O(2^n) exponential: the explosion"]
F --> G["O(n!) factorial: the ultimate 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) constant
Same time for any n. Array index, hash lookup, stack push. Like a light switch. Deep dive: Open
O(logn) logarithmic
Halves the problem each step. Binary search, balanced BST. Like finding a word in a dictionary. Deep dive: Open
O(n) linear
One pass over the input. Linear search, finding the max. Like reading a book page by page. Deep dive: Open
O(nlogn) linearithmic
Divide, then merge. Merge sort, heap sort. Like organising a library shelf. Deep dive: Open
O(n2) quadratic
Every pair. Bubble sort, nested loops. Like handshakes at a party. Deep dive: Open
O(2n) exponential
Two choices per item. All subsets, naive Fibonacci. Like a chain letter doubling. Deep dive: Open
O(n!) factorial
Every ordering. All permutations, brute-force travelling salesman. Like every seating plan. Deep dive: Open
Algorithms and code shapes
Class
Classic algorithms
Code shape
O(1)
Array access by index, hash table lookup, stack push and pop
No loop that depends on n
O(logn)
Binary search, balanced BST operations, fast power
Divide the search space by 2 each round
O(n)
Linear search, array traversal, finding the max
One loop over all n items
O(nlogn)
Merge sort, heap sort, quicksort on average
Divide and conquer with a linear merge, or n heap operations
O(n2)
Bubble sort, selection sort, checking all pairs
Two nested loops over n
O(2n)
Naive recursive Fibonacci, power set, Tower of Hanoi
Two recursive calls per item
O(n!)
All permutations, brute-force travelling salesman, brute-force N-Queens
Try every ordering of the n items
The numbers
The big comparison table
Class
n = 10
n = 100
n = 1,000
n = 106
O(1)
1
1
1
1
O(logn)
3.3
6.6
10
20
O(n)
10
100
1,000
106
O(nlogn)
33
664
9,966
2×107
O(n2)
100
10,000
106
1012
O(2n)
1,024
1.3×1030
1.1×10301
about 10301,030
O(n!)
3,628,800
9.3×10157
about 102,568
about 105,565,709
Operation counts with log2. The bottom two rows are finite numbers, but no computer could ever finish them.
These three anchors let you fill in most of the table by hand: nlogn at a million is about 106×20=2×107.
Time budget
What n can I afford in one second?
The one-second rule
f(n)≤108simple steps≈1 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)≤108 for each class.
Class
Largest n in about 1 second
Why
O(1)
any n
The cost never grows
O(logn)
any practical n
log21018≈60
O(n)
108
One step per item
O(nlogn)
about 4.5 million
4.5×106×22≈108
O(n2)
10,000
104×104=108
O(n3)
about 460
4643≈108
O(2n)
26
226≈6.7×107
O(n!)
11
11!≈4×107, but 12!≈4.8×108
The same classes as wall-clock time at n = 1,000,000
Class
Steps
Time at 108 per second
O(logn)
20
0.2 microseconds
O(n)
106
0.01 seconds
O(nlogn)
2×107
0.2 seconds
O(n2)
1012
about 2.8 hours
O(2n)
10301,030
never
Scaling
What happens when n doubles
Class
Effect of doubling n
1 second at n becomes
O(1)
No change
1 second
O(logn)
One more step
a hair over 1 second
O(n)
Twice the work
2 seconds
O(nlogn)
A bit more than twice
about 2.1 seconds
O(n2)
Four times the work
4 seconds
O(2n)
The work is squared
2n seconds
O(n!)
Multiplied by (n+1)(n+2)⋯(2n)
astronomical
Where those factors come from
log2(2n)=log2n+1(2n)2=4n222n=(2n)22n+1=2⋅2n
For exponential growth, adding one item already doubles the work, and doubling n squares it.
Constraints
From the constraint to the target
n is at most
Aim for
Typical problems
10 to 11
O(n!) or O(2n)
Permutations, N-Queens, Sudoku solver
20 to 25
O(2n)
Subsets, combination sum, partition problems
100 to 500
O(n3)
Floyd-Warshall, DP with three indices
1,000 to 10,000
O(n2)
All pairs, simple 2D DP
105 to 106
O(nlogn) or O(n)
Sorting, heaps, two pointers, sliding window
108 and more
O(logn) or 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
flowchart TD
S["Read the largest allowed n"] --> Q1{"n <= 11?"}
Q1 -- yes --> A1["O(n!) or O(2^n): brute force is fine"]
Q1 -- no --> Q2{"n <= 25?"}
Q2 -- yes --> A2["O(2^n): subsets, bitmasks"]
Q2 -- no --> Q3{"n <= 500?"}
Q3 -- yes --> A3["O(n^3): triple loops"]
Q3 -- no --> Q4{"n <= 10^4?"}
Q4 -- yes --> A4["O(n^2): all pairs"]
Q4 -- no --> Q5{"n <= 10^6?"}
Q5 -- yes --> A5["O(n log n) or O(n)"]
Q5 -- no --> A6["O(log n) or O(1)"]
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?
flowchart TD
Q1{"Does the work depend on n at all?"} -- no --> C1["O(1)"]
Q1 -- yes --> Q2{"Does each step cut n by a constant factor?"}
Q2 -- yes --> C2["O(log n)"]
Q2 -- no --> Q3{"Branching recursion over the items?"}
Q3 -- "every ordering" --> C7["O(n!)"]
Q3 -- "two choices per item" --> C6["O(2^n)"]
Q3 -- no --> Q4{"Two loops nested over n?"}
Q4 -- yes --> C5["O(n^2)"]
Q4 -- no --> Q5{"log n levels of O(n) work, or a sort?"}
Q5 -- yes --> C4["O(n log n)"]
Q5 -- no --> C3["O(n): one pass"]
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 permutationsdeffirst(arr): # O(1)return arr[0]defhalvings(n): # O(log n) steps = 0while n > 1: n //= 2 steps += 1return stepsdeftotal(arr): # O(n) s = 0for x in arr: s += xreturn sdefsort_it(arr): # O(n log n)returnsorted(arr)defcount_pairs(arr): # O(n^2) pairs = 0for i inrange(len(arr)):for j inrange(i + 1, len(arr)): pairs += 1return pairsdefcount_subsets(arr): # O(2^n): two calls per itemifnot arr:return1 rest = arr[1:]returncount_subsets(rest) + count_subsets(rest) # skip it, take itdefcount_orders(arr): # O(n!)returnsum(1for _ inpermutations(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
1Count3n² + 5n + 2
2Drop constantsn² + n + 1
3Keep the biggest termn²
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)
The right side holds once n2≥5n+2, which is true from n=6. Both bounds use n2, so the cost is Θ(n2).
Rules that hold
Loops one after another add: O(n)+O(m)=O(n+m).
Nested loops multiply: O(n)×O(m)=O(nm).
The base of a log does not matter: log2n and log10n differ by a constant.
Keep separate inputs separate: a loop over n and one over m is not O(n).
Rules that do not
The base of an exponential matters: 3n=1.5n⋅2n, so O(3n)=O(2n).
An exponent on n matters: O(n2) is not O(n).
A single loop is not always 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 100n against n2, the quadratic is faster until n=100. Python's sort uses insertion sort on short runs for exactly this reason.
Constants and memory
Two 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(nlogn) on average but O(n2) in the worst case; hash maps are O(1) on average but O(n) when everything collides.
Amortised cost
A dynamic array append is occasionally O(n) when it resizes, but O(1) averaged over many appends.
Where a slower class overtakes a faster one
100n≤n2⟺n≥1001000nlog2n≤n2⟺n≳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<logn<n<nlogn<n2<2n<n!, from the flat line to the explosion.
Big O is an upper bound, Big Ω a lower bound, Big Θ both at once.
At n=106: 1, 20, 106, 2×107, 1012, and two counts that can never finish.
In about a second (108 steps): O(n) to 108, O(nlogn) to about 4.5 million, O(n2) to 104, O(2n) to 26, 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.