# big o

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

source: https://learning.anthnydas.com/algos/big-o/

## tl;dr

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

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

> **interactive figure:** 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).

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

double n to 16. O(1) stays put. log n gains one step. n doubles. n log n a bit more than doubles. n² goes up four times.

double again, to 32, and each row changes the same way it did before. that pattern is what big o names: how the work grows when n grows, not how much work there is.

constants drop out. 3n + 5 takes 29, 53, then 101 steps: close to double each time, like n. so 3n + 5 is O(n), and so is n + 1,000.

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

> **interactive figure:** 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

> **interactive figure:** 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.

```text
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

> **interactive figure:** 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² + 100n` is 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](/algos/binary-search/) takes 20 looks for a million items.

## complexity

> **interactive figure:** 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](/algos/quicksort/) is O(n²) at worst, when its pivots keep landing at the ends
- **best case.** the least. [insertion sort](/algos/insertion-sort/) on sorted input makes n - 1 comparisons, O(n)
- **average case.** the work on a typical input. a [hash table](/ds/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](/ds/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](/algos/merge-sort/) needs an O(n) buffer, while [heap sort](/algos/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                                                   |
| binary search       | space                                 | `O(1)`             | two indexes                                                                    |
| insertion sort      | time                                  | `O(n²)`            | random or reversed input                                                       |
| insertion sort      | sorted input                          | `O(n)`             | n - 1 comparisons, no shifts                                                   |
| insertion sort      | nearly sorted                         | `O(n + k)`         | k pairs out of order, one shift each                                           |
| insertion sort      | space                                 | `O(1)`             | in place, one item in hand                                                     |
| merge sort          | time                                  | `O(n log n)`       | best and worst case                                                            |
| merge sort          | space                                 | `O(n)`             | the merge buffer                                                               |
| quicksort           | average                               | `O(n log n)`       | about 1.39 n log₂ n comparisons                                                |
| quicksort           | worst                                 | `O(n²)`            | a pivot at one end, every time                                                 |
| quicksort           | space                                 | `O(log n)`         | the stack, recursing on the smaller side                                       |
| heap sort           | time                                  | `O(n log n)`       | best, average and worst                                                        |
| heap sort           | space                                 | `O(1)`             | in place, no buffer, no recursion                                              |
| heap sort           | 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                        |
| two pointers        | space                                 | `O(1)`             | two indexes, nothing else                                                      |
| sliding window      | one pass                              | `O(n)`             | every item enters once and leaves at most once                                 |
| sliding window      | one slide                             | `O(1)`             | add what enters, drop what leaves                                              |
| sliding window      | extra space                           | `O(1)`             | a sum, or a count per letter                                                   |
| sliding window      | 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 |
| bfs                 | 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                       |
| dfs                 | 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                 |
| dijkstra            | space                                 | `O(n + m)`         | dist, parent and done per vertex, and a heap of at most m + 1 entries          |
| dijkstra            | 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                   |
| a\*                 | 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           |
| dynamic programming | 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                                                     |
| dynamic array       | push / pop                            | `O(1)`             | at the end. push is amortized                                                  |
| dynamic array       | grow                                  | `O(n)`             | copies everything, once per doubling                                           |
| dynamic array       | insert / remove at i                  | `O(n)`             | everything after i slides over                                                 |
| linked list         | push / pop front                      | `O(1)`             | one arrow changes                                                              |
| linked list         | insert / remove after a node you hold | `O(1)`             | an arrow or two change, nothing slides                                         |
| linked list         | get(i)                                | `O(i)`             | walk from the head, no jumping                                                 |
| linked list         | push back                             | `O(n)`             | without a tail pointer, a walk to the end                                      |
| stack + queue       | push                                  | `O(1)`             | amortized, at either end                                                       |
| stack + queue       | pop                                   | `O(1)`             | at either end                                                                  |
| stack + queue       | peek / get(i)                         | `O(1)`             | (head + i) % capacity                                                          |
| stack + queue       | grow                                  | `O(n)`             | copies everything, once per doubling                                           |
| stack + queue       | insert in the middle                  | `O(n)`             | only the ends are cheap                                                        |
| hash table          | get                                   | `O(1)`             | average. O(n) if every key collides                                            |
| hash table          | put                                   | `O(1)`             | average, amortized over the resizes                                            |
| hash table          | remove                                | `O(1)`             | average                                                                        |
| hash table          | resize                                | `O(n)`             | every key placed again, once per doubling                                      |
| hash table          | min, max                              | `O(n)`             | no order to use, so check every key                                            |
| heap                | peek                                  | `O(1)`             | the smallest is at index 0                                                     |
| heap                | push                                  | `O(log n)`         | at most one swap per level                                                     |
| heap                | pop                                   | `O(log n)`         | the last item goes on top and sinks                                            |
| heap                | build from n items                    | `O(n)`             | most items sit near the bottom                                                 |
| heap                | find an item                          | `O(n)`             | a heap isn't sorted                                                            |
| binary search tree  | search                                | `O(log n)`         | on average, one node per level                                                 |
| binary search tree  | insert / remove                       | `O(log n)`         | on average, a walk and a few links                                             |
| binary search tree  | walk in order                         | `O(n)`             | the keys come out sorted                                                       |
| binary search tree  | min / max                             | `O(log n)`         | on average, as far left or right as it goes                                    |
| binary search tree  | sorted inserts                        | `O(n)`             | the tree turns into a stick                                                    |
| trie                | insert                                | `O(L)`             | a node per letter, L letters                                                   |
| trie                | search                                | `O(L)`             | however many words there are                                                   |
| trie                | starts with                           | `O(L)`             | a prefix is a path too                                                         |
| trie                | remove                                | `O(L)`             | unmark, then cut what's left                                                   |
| union-find          | find                                  | `O(α(n))`          | amortized, under 5 for any real n                                              |
| union-find          | union                                 | `O(α(n))`          | two finds and one link                                                         |
| union-find          | 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                                   |
| graphs as data      | neighbors                             | `O(deg u)`         | u's row of the lists. the matrix reads n cells                                 |
| graphs as data      | 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](/algos/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](https://leetcode.com/problems/contains-duplicate/): every pair is O(n²), sorting first O(n log n), a set O(n)
- [two sum](https://leetcode.com/problems/two-sum/): every pair is O(n²), a hash map of what you've seen O(n)
- [valid anagram](https://leetcode.com/problems/valid-anagram/): sort both O(n log n), count the letters O(n)
- [maximum subarray](https://leetcode.com/problems/maximum-subarray/): every subarray O(n²), one pass with a running sum O(n)
- [climbing stairs](https://leetcode.com/problems/climbing-stairs/): plain recursion is exponential, remembering each answer O(n)
- [fibonacci number](https://leetcode.com/problems/fibonacci-number/): the same as climbing stairs

## related

- https://learning.anthnydas.com/algos/binary-search.md
- https://learning.anthnydas.com/algos/insertion-sort.md
- https://learning.anthnydas.com/algos/merge-sort.md
- https://learning.anthnydas.com/ds/hash-table.md
- https://learning.anthnydas.com/ds/dynamic-array.md
- https://learning.anthnydas.com/algos/dynamic-programming.md
