algosbasics
big o
how the work grows as the input grows, and why the constants drop out.
how the work grows when n grows. drop the constants and the smaller terms, and keep the shape.
- constant
- O(1) the same at any n
- logarithmic
- O(log n) one more step when n doubles
- linear
- O(n) doubles when n doubles
- n log n
- O(n log n) a bit more than double
- quadratic
- O(n²) four times when n doubles
- exponential
- O(2ⁿ) squares when n doubles
- comparing two ideas before writing either
- guessing if a solution is fast enough
- reading the cost tiles on every page here
on this page
the idea
big o answers one question about an algorithm: when the input gets bigger, how much more work does it do? count the steps for n items, double n, and see what the count does. it stays the same, gains a step, doubles, or worse. that change is the algorithm’s class, and it doesn’t care how fast the machine is.
an animation: a table of step counts for five classes at n = 8, 16 and 32. O(1) stays at 1. O(log n) goes 3, 4, 5, one more each time. O(n) goes 8, 16, 32, doubling. O(n log n) goes 24, 64, 160, a bit more than double. O(n²) goes 64, 256, 1,024, four times each time. then a sixth row, 3n + 5, goes 29, 53, 101: close to double each time, like O(n).
watch it run
count the steps yourself. pick a loop and an n, then step through it: each square is one call to step(), with a row for each pass of the outer loop. the shape is the class: a line, a square, a few, or a few per row.
nothing has run yet. in all, 8 × 8 = 64 steps: n for every i.
- steps
- 0 of 64
one_loop(n): for i in 0 .. n - 1: step() # n steps loop_in_a_loop(n): for i in 0 .. n - 1: for j in 0 .. n - 1: step() # n * n steps halving_loop(n): m = n while m > 0: step() # one step per bit of n m = m // 2 loop_around_halving(n): for i in 0 .. n - 1: m = n while m > 0: step() # n times the bits of n m = m // 2an interactive stepper over four loops: one loop, a loop in a loop, a halving loop, and a loop around a halving loop, with n set to 4, 8 or 16. each step lights one square in a grid, a row per pass of the outer loop, and the count of steps runs up to n, n times n, the number of bits in n, or n times that.
try it
which class is this in?
for i in 0 .. n - 1: step() for j in 0 .. n - 1: step()
pick one.
a practice exercise with short loops: name the class a snippet is in, or say how many steps it takes at n = 16 when it takes a given number at n = 8.
pseudocode
the four loops from the stepper. each step() stands for any work that takes the same time whatever n is.
one_loop(n):
for i in 0 .. n - 1:
step() # n steps
loop_in_a_loop(n):
for i in 0 .. n - 1:
for j in 0 .. n - 1:
step() # n * n steps
halving_loop(n):
m = n
while m > 0:
step() # one step per bit of n
m = m // 2
loop_around_halving(n):
for i in 0 .. n - 1:
m = n
while m > 0:
step() # n times the bits of n
m = m // 2at n = 16 they take 16, 256, 5 and 80 steps. double n to 32 and they take 32, 1,024, 6 and 192: twice as many, four times, one more, and a bit more than twice.
the key step up close
constants drop out
big o keeps how a count grows and drops what it’s multiplied by. 3n + 5 and n both double when n doubles, so both are O(n). the 3 depends on what a step costs on this machine, in this language, and that’s a different question. the 5 stops mattering as soon as n is big.
the biggest term wins
- 100n
- 5,000 steps
- n²
- 2,500 steps
a chart with linear axes from n = 0 to 200: 100n is a straight line and n² is a curve that bends up. 100n starts out bigger: 5,000 against 2,500 at n = 50. they meet at n = 100, at 10,000 steps each. past that n² pulls ahead: 40,000 against 20,000 at n = 200, twice as many. a slider reads both at any n.
- 100n starts out bigger than n²: at n = 50 it’s 5,000 steps against 2,500
- at n = 100 they meet, at 10,000 steps each
- past that n² pulls away: twice as many at 200, ten times as many at 1,000
- so a cost like
n² + 100nis O(n²). the smaller term mattered for small n and stops mattering as n grows
why halving is log n
the halving loop takes one step per bit of n: 16 is 10000 in binary, five bits, and the loop runs at m = 16, 8, 4, 2 and 1. doubling n adds one bit, so it adds one step. that’s O(log n), and it’s why binary search takes 20 looks for a million items.
complexity
- O(1)
- 1 step
- O(log n)
- 4 steps
- O(n)
- 16 steps
- O(n log n)
- 64 steps
- O(n²)
- 256 steps
- O(2ⁿ)
- 65,536 steps
a chart of steps against n, from 1 to 1,024 on a doubling scale, with the six classes. O(1) stays flat at 1 and O(log n) climbs to 10. O(2ⁿ) leaves the top of the chart first, then O(n²), O(n log n) and O(n). a slider reads every class at one n: at 16 they're 1, 4, 16, 64, 256 and 65,536.
the same six classes at three sizes:
| class | n = 10 | n = 1,000 | n = 1,000,000 |
|---|---|---|---|
| O(1) | 1 | 1 | 1 |
| O(log n) | 3.32 | 9.97 | 19.93 |
| O(n) | 10 | 1,000 | 1,000,000 |
| O(n log n) | 33.22 | 9,965.78 | 19,931,568.57 |
| O(n²) | 100 | 1,000,000 | 1,000,000,000,000 |
| O(2ⁿ) | 1,024 | a 302-digit number | a 301,030-digit number |
at a million items, an n² algorithm does a trillion steps where an n log n one does about twenty million. that gap, not the speed of the machine, is what decides whether a program finishes.
best, worst, average and amortized
a class can describe different things, so say which:
- worst case. the most work any input of size n can cause. quicksort is O(n²) at worst, when its pivots keep landing at the ends
- best case. the least. insertion sort on sorted input makes n - 1 comparisons, O(n)
- average case. the work on a typical input. a hash table finds a key in O(1) on average, but O(n) if every key lands in one bucket
- amortized. the cost per operation over a long run. one push onto a dynamic array can copy everything, but n pushes copy fewer than 2n items, so each push is O(1) amortized
space
the same counting works for memory. merge sort needs an O(n) buffer, while heap sort sorts in O(1) extra space. recursion counts too: every call waiting on the stack holds memory.
every page’s costs
every operation’s cost on the algorithm and data structure pages here, read from their tiles:
| page | operation | cost | note |
|---|---|---|---|
| binary search | time | O(log n) | 20 looks for a million items |
| space | O(1) | two indexes | |
| insertion sort | time | O(n²) | random or reversed input |
| sorted input | O(n) | n - 1 comparisons, no shifts | |
| nearly sorted | O(n + k) | k pairs out of order, one shift each | |
| space | O(1) | in place, one item in hand | |
| merge sort | time | O(n log n) | best and worst case |
| space | O(n) | the merge buffer | |
| quicksort | average | O(n log n) | about 1.39 n log₂ n comparisons |
| worst | O(n²) | a pivot at one end, every time | |
| space | O(log n) | the stack, recursing on the smaller side | |
| heap sort | time | O(n log n) | best, average and worst |
| space | O(1) | in place, no buffer, no recursion | |
| build | O(n) | fewer than n swaps | |
| two pointers | time | O(n) | at most n - 1 sums, against n(n - 1) / 2 for every pair |
| space | O(1) | two indexes, nothing else | |
| sliding window | one pass | O(n) | every item enters once and leaves at most once |
| one slide | O(1) | add what enters, drop what leaves | |
| extra space | O(1) | a sum, or a count per letter | |
| from scratch | O(n·k) | every window of k, summed again | |
| bfs | time | O(n + m) | every reached vertex out of the queue once, every edge looked at from each end |
| space | O(n) | a queue of n slots, dist and parent | |
| dfs | time | O(n + m) | each vertex visited once, each list entry looked at once |
| space | O(n) | a seen flag per vertex, and the stack | |
| dijkstra | time | O((n + m) log n) | a push and a pop per relax that lowers a dist, each log n deep |
| space | O(n + m) | dist, parent and done per vertex, and a heap of at most m + 1 entries | |
| without a heap | O(n²) | scan every vertex for the closest one, n times. fine when m is near n² | |
| a* | per cell | O(log n) | the heap. bfs pays O(1), so a* wins by touching fewer cells |
| space | O(n) | g, parent and done for every cell found, and the heap | |
| dynamic programming | time | O(m × n) | a cell for each pair of prefixes, each filled once from three others |
| space | O(m × n) | the table, or two rows when only the distance is needed | |
| dynamic array | get / set | O(1) | start + i slots, no search |
| push / pop | O(1) | at the end. push is amortized | |
| grow | O(n) | copies everything, once per doubling | |
| insert / remove at i | O(n) | everything after i slides over | |
| linked list | push / pop front | O(1) | one arrow changes |
| insert / remove after a node you hold | O(1) | an arrow or two change, nothing slides | |
| get(i) | O(i) | walk from the head, no jumping | |
| push back | O(n) | without a tail pointer, a walk to the end | |
| stack + queue | push | O(1) | amortized, at either end |
| pop | O(1) | at either end | |
| peek / get(i) | O(1) | (head + i) % capacity | |
| grow | O(n) | copies everything, once per doubling | |
| insert in the middle | O(n) | only the ends are cheap | |
| hash table | get | O(1) | average. O(n) if every key collides |
| put | O(1) | average, amortized over the resizes | |
| remove | O(1) | average | |
| resize | O(n) | every key placed again, once per doubling | |
| min, max | O(n) | no order to use, so check every key | |
| heap | peek | O(1) | the smallest is at index 0 |
| push | O(log n) | at most one swap per level | |
| pop | O(log n) | the last item goes on top and sinks | |
| build from n items | O(n) | most items sit near the bottom | |
| find an item | O(n) | a heap isn't sorted | |
| binary search tree | search | O(log n) | on average, one node per level |
| insert / remove | O(log n) | on average, a walk and a few links | |
| walk in order | O(n) | the keys come out sorted | |
| min / max | O(log n) | on average, as far left or right as it goes | |
| sorted inserts | O(n) | the tree turns into a stick | |
| trie | insert | O(L) | a node per letter, L letters |
| search | O(L) | however many words there are | |
| starts with | O(L) | a prefix is a path too | |
| remove | O(L) | unmark, then cut what's left | |
| union-find | find | O(α(n)) | amortized, under 5 for any real n |
| union | O(α(n)) | two finds and one link | |
| connected | O(α(n)) | two finds, compare the roots | |
| graphs as data | has edge | O(1) | one cell of the matrix. the lists scan a row |
| neighbors | O(deg u) | u's row of the lists. the matrix reads n cells | |
| add, remove | O(1) | two cells of the matrix. the lists scan a row first |
pitfalls
- big o isn’t speed. below n = 100, the “slower” n² beats 100n. for small inputs constants matter, which is why fast sorts hand short runs to insertion sort
- hidden loops.
x in some_list, a slice, or adding to a string can walk or copy everything. one inside a loop makes the loop O(n²) - the base of a log doesn’t matter: log₂ n is about 3.32 times log₁₀ n, a constant, so both are O(log n)
- two inputs keep two letters. walking a list of n and one of m is O(n + m). every pair between them is O(n · m), not O(n²)
- “O” is an upper bound. a single loop is also O(n²), just not usefully. people usually mean the tightest class that fits
variants
- big Θ and big Ω. O caps the growth from above, Ω from below, and Θ pins it from both sides. merge sort is Θ(n log n): never more, never less. most people say O when they mean Θ
- amortized against average. amortized is a promise about every long run of operations. average is about typical inputs, and an unlucky input can still be slow
- the input’s size. n is usually the number of items, but for a number like a prime check it’s the number of digits. trying every divisor up to n is linear in n, but exponential in the digits
practice
each of these has a slow answer and a fast one. write the slow one, name its class, then find the faster one:
- contains duplicate (opens in a new tab): every pair is O(n²), sorting first O(n log n), a set O(n)
- two sum (opens in a new tab): every pair is O(n²), a hash map of what you’ve seen O(n)
- valid anagram (opens in a new tab): sort both O(n log n), count the letters O(n)
- maximum subarray (opens in a new tab): every subarray O(n²), one pass with a running sum O(n)
- climbing stairs (opens in a new tab): plain recursion is exponential, remembering each answer O(n)
- fibonacci number (opens in a new tab): the same as climbing stairs