Two programs can solve the same problem, yet one finishes instantly and the other takes hours on big inputs. Complexity is how we describe that difference.
- Time complexity: how the number of steps grows as the input size \(n\) grows.
- Space complexity: how the extra memory grows as \(n\) grows.
We write both with Big-O notation, such as \(O(n)\). Big-O keeps only the shape of the growth and ignores small details.
Three rules for reading Big-O
- Count steps in terms of \(n\). A step is one simple action: a comparison, an addition, a lookup.
- Drop constants. \(3n\) steps and \(n\) steps both grow in a straight line, so both are \(O(n)\).
- Keep the biggest term. \(n^2 + 4n + 10\) is \(O(n^2)\), because for large \(n\) the \(n^2\) part swamps the rest.
From slow growth (good) to fast growth (bad):
\[ O(1) < O(\log n) < O(n) < O(n \log n) < O(n^2) < O(2^n) \]
Auxiliary space means the extra memory an algorithm creates, not counting the input itself. When people say “space complexity”, they usually mean this. Function calls waiting to finish also use memory (the call stack), so they count too.
1. Constant: \(O(1)\)
Situation: taking the first book from a shelf. It makes no difference whether the shelf holds 10 books or 10 million.
first_item <- function(items) {
items[1] # R counts from 1
}def first_item(items):
return items[0]- Time: one lookup, always. \(O(1)\).
- Space: nothing new is stored. \(O(1)\).
2. Linear: \(O(n)\)
Situation: adding up the prices on a receipt. Twice as many items means twice as much work.
total <- function(prices) {
s <- 0
for (p in prices) { # runs n times
s <- s + p # one addition each time
}
s
}def total(prices):
s = 0
for p in prices: # runs n times
s += p # one addition each time
return sLet us count the steps for lists of different sizes:
| \(n\) | Additions |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
- Time: the number of steps equals \(n\). \(O(n)\).
- Space: only the variable
s, however long the list is. \(O(1)\).
A single loop over the input is usually \(O(n)\). If the loop also builds a new list of size \(n\), the space becomes \(O(n)\) too.
3. Quadratic: \(O(n^2)\)
Situation: everyone in a room shakes hands with everyone else. With \(n\) people, how many handshakes?
handshakes <- function(people) {
n <- length(people)
count <- 0
for (i in 1:(n - 1)) {
for (j in (i + 1):n) { # each pair once
count <- count + 1
}
}
count
}def handshakes(people):
count = 0
for i in range(len(people)):
for j in range(i + 1, len(people)): # each pair once
count += 1
return countRunning it:
| \(n\) people | Handshakes |
|---|---|
| 10 | 45 |
| 100 | 4950 |
| 1000 | 499500 |
Multiplying the people by 10 multiplies the work by about 100. That is the signature of \(n^2\). The exact count is \(\frac{n(n-1)}{2}\), and after dropping the constant \(\frac12\) and the smaller term, we are left with \(O(n^2)\).
- Time: \(O(n^2)\).
- Space: only the counters. \(O(1)\).
Any “compare every item with every other item” idea ends up here, for example checking a list for duplicates with two loops.
Time–space trade-off. The duplicate check can be done in \(O(n)\) time by remembering the items already seen in a set. We buy the speed with \(O(n)\) extra memory.
4. Logarithmic: \(O(\log n)\)
Situation: a friend thinks of a number from 1 to 100 and answers only “higher” or “lower”. The smart move is to always guess the middle.
guess <- function(secret, low = 1, high = 100) {
guesses <- 0
while (low <= high) {
mid <- (low + high) %/% 2 # guess the middle
guesses <- guesses + 1
if (mid == secret) {
return(guesses)
} else if (mid < secret) {
low <- mid + 1 # throw away the lower half
} else {
high <- mid - 1 # throw away the upper half
}
}
}def guess(secret, low=1, high=100):
guesses = 0
while low <= high:
mid = (low + high) // 2 # guess the middle
guesses += 1
if mid == secret:
return guesses
elif mid < secret:
low = mid + 1 # throw away the lower half
else:
high = mid - 1 # throw away the upper halfEvery guess removes half of the remaining numbers:
\[ 100 \to 50 \to 25 \to 13 \to 7 \to 4 \to 2 \to 1 \]
For the secret number 73 this takes 6 guesses, and for any number from 1 to 100 it never takes more than 7. How slowly does that grow?
| Numbers to search | Guesses needed (at most) |
|---|---|
| 100 | 7 |
| 1000 | 10 |
| 1000000 | 20 |
A million possibilities need just 20 guesses. This is binary search, and halving is what makes it \(O(\log n)\).
- Time: \(O(\log n)\). (Here \(\log\) means \(\log_2\); the base only changes a constant.)
- Space:
low,high,mid,guesses. \(O(1)\).
Binary search only works when the data is sorted. Higher/lower answers mean nothing in a shuffled list.
5. Linearithmic: \(O(n \log n)\)
Situation: sorting a pile of 8 exam papers by splitting the pile in half again and again, then merging the sorted halves. This is merge sort.
8 papers
split → 4 + 4
split → 2 + 2 + 2 + 2
split → 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
merge back up, sorting as we go- Halving 8 papers down to single papers takes \(\log_2 8 = 3\) levels.
- On every level, merging touches each paper once: about \(n\) steps.
- Total: \(n \times \log n\) steps, so \(O(n \log n)\).
The merged halves need temporary room for the papers, so the space is \(O(n)\).
In practice we rarely write this ourselves, because the built-in sorting (sort() in R, sorted() in Python) is already about \(O(n \log n)\).
6. Exponential: \(O(2^n)\)
Situation: the Fibonacci numbers, where each number is the sum of the previous two (0, 1, 1, 2, 3, 5, 8, …). The direct translation of that rule into code is:
fib <- function(n) {
if (n <= 1) {
return(n)
}
fib(n - 1) + fib(n - 2) # two calls every time
}def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2) # two calls every timeEach call starts two more calls, so the work doubles at every level. Counting the calls:
fib(n) |
Value | Function calls |
|---|---|---|
| 5 | 5 | 15 |
| 10 | 55 | 177 |
| 20 | 6765 | 21891 |
| 25 | 75025 | 242785 |
Adding just 5 to \(n\) made the work about 11 times bigger. Growth like this quickly becomes impossible to run. The tight bound is a little smaller than \(2^n\) (about \(1.6^n\)), but the lesson is the same: this is exponential.
- Time: \(O(2^n)\) (as a simple upper bound).
- Space: although there are many calls over time, finished calls free their memory. At any moment only one chain of at most \(n\) calls is waiting. \(O(n)\).
The slowness comes from solving the same small problems again and again. Remember each answer the first time (called memoization) and fib drops to \(O(n)\) time.
Cheat sheet
| What the code does | Time | Extra space |
|---|---|---|
| One lookup or one arithmetic step | \(O(1)\) | \(O(1)\) |
| Halving the problem each step | \(O(\log n)\) | \(O(1)\) (loop) |
| One loop over the input | \(O(n)\) | \(O(1)\) |
| Split in half, then merge | \(O(n \log n)\) | \(O(n)\) |
| Two nested loops over the input | \(O(n^2)\) | \(O(1)\) |
| Two recursive calls per step | \(O(2^n)\) | \(O(n)\) |
References
- Python Wiki, Time Complexity, costs of built-in operations.
- Wikipedia, Big O notation.
- Wikipedia, Binary search algorithm.