algosbasics

big o

how the work grows as the input grows, and why the constants drop out.

report a mistake
.md

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
reach for it
  • comparing two ideas before writing either
  • guessing if a solution is fast enough
  • reading the cost tiles on every page here
on this page
  1. the idea
  2. watch it run
  3. try it
  4. pseudocode
  5. the key step up close
  6. complexity
  7. every page’s costs
  8. pitfalls
  9. variants
  10. practice

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.

five ways the work can grow, at n = 8: 1, 3, 8, 24 and 64 steps. at this size they’re all small.

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
pseudocode
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 // 2

an 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.

0 / 0 right

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.

pseudocode
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 // 2

at 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

010k20k30k40k050100150200n = 100
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.

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

0204060801001321024O(n)O(n log n)O(n²)O(2ⁿ)
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:

classn = 10n = 1,000n = 1,000,000
O(1)111
O(log n)3.329.9719.93
O(n)101,0001,000,000
O(n log n)33.229,965.7819,931,568.57
O(n²)1001,000,0001,000,000,000,000
O(2ⁿ)1,024a 302-digit numbera 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:

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:

every page's costs
pageoperationcostnote
binary searchtimeO(log n)20 looks for a million items
spaceO(1)two indexes
insertion sorttimeO(n²)random or reversed input
sorted inputO(n)n - 1 comparisons, no shifts
nearly sortedO(n + k)k pairs out of order, one shift each
spaceO(1)in place, one item in hand
merge sorttimeO(n log n)best and worst case
spaceO(n)the merge buffer
quicksortaverageO(n log n)about 1.39 n log₂ n comparisons
worstO(n²)a pivot at one end, every time
spaceO(log n)the stack, recursing on the smaller side
heap sorttimeO(n log n)best, average and worst
spaceO(1)in place, no buffer, no recursion
buildO(n)fewer than n swaps
two pointerstimeO(n)at most n - 1 sums, against n(n - 1) / 2 for every pair
spaceO(1)two indexes, nothing else
sliding windowone passO(n)every item enters once and leaves at most once
one slideO(1)add what enters, drop what leaves
extra spaceO(1)a sum, or a count per letter
from scratchO(n·k)every window of k, summed again
bfstimeO(n + m)every reached vertex out of the queue once, every edge looked at from each end
spaceO(n)a queue of n slots, dist and parent
dfstimeO(n + m)each vertex visited once, each list entry looked at once
spaceO(n)a seen flag per vertex, and the stack
dijkstratimeO((n + m) log n)a push and a pop per relax that lowers a dist, each log n deep
spaceO(n + m)dist, parent and done per vertex, and a heap of at most m + 1 entries
without a heapO(n²)scan every vertex for the closest one, n times. fine when m is near n²
a*per cellO(log n)the heap. bfs pays O(1), so a* wins by touching fewer cells
spaceO(n)g, parent and done for every cell found, and the heap
dynamic programmingtimeO(m × n)a cell for each pair of prefixes, each filled once from three others
spaceO(m × n)the table, or two rows when only the distance is needed
dynamic arrayget / setO(1)start + i slots, no search
push / popO(1)at the end. push is amortized
growO(n)copies everything, once per doubling
insert / remove at iO(n)everything after i slides over
linked listpush / pop frontO(1)one arrow changes
insert / remove after a node you holdO(1)an arrow or two change, nothing slides
get(i)O(i)walk from the head, no jumping
push backO(n)without a tail pointer, a walk to the end
stack + queuepushO(1)amortized, at either end
popO(1)at either end
peek / get(i)O(1)(head + i) % capacity
growO(n)copies everything, once per doubling
insert in the middleO(n)only the ends are cheap
hash tablegetO(1)average. O(n) if every key collides
putO(1)average, amortized over the resizes
removeO(1)average
resizeO(n)every key placed again, once per doubling
min, maxO(n)no order to use, so check every key
heappeekO(1)the smallest is at index 0
pushO(log n)at most one swap per level
popO(log n)the last item goes on top and sinks
build from n itemsO(n)most items sit near the bottom
find an itemO(n)a heap isn't sorted
binary search treesearchO(log n)on average, one node per level
insert / removeO(log n)on average, a walk and a few links
walk in orderO(n)the keys come out sorted
min / maxO(log n)on average, as far left or right as it goes
sorted insertsO(n)the tree turns into a stick
trieinsertO(L)a node per letter, L letters
searchO(L)however many words there are
starts withO(L)a prefix is a path too
removeO(L)unmark, then cut what's left
union-findfindO(α(n))amortized, under 5 for any real n
unionO(α(n))two finds and one link
connectedO(α(n))two finds, compare the roots
graphs as datahas edgeO(1)one cell of the matrix. the lists scan a row
neighborsO(deg u)u's row of the lists. the matrix reads n cells
add, removeO(1)two cells of the matrix. the lists scan a row first

pitfalls

variants

practice

each of these has a slow answer and a fast one. write the slow one, name its class, then find the faster one: