Big-O: counting how work grows with input
1 Why we count steps, not seconds
Two students solve the same problem. Both programs give the right answer on every example. One gets Accepted and the other gets Time Limit Exceeded (TLE), because one program does far more work than the other.
We want to know this before we submit. A stopwatch does not help much. The same code runs faster on a new laptop than on an old one, and faster in C++ than in Python.
So we count steps instead. A step is one simple action, such as an addition, a comparison or reading one array value. The count depends mostly on the size of the input, which we call n. For an array, n is how many values it holds.
2 One question, two methods
The problem Contains Duplicate asks whether any value appears at least twice in an array. We answer it in two ways.
The first method checks every pair. It compares each value with every value after it. Here it is on nums = [4, 1, 7, 3], which has no duplicate:
i | j | nums[i] | nums[j] | Equal? | Comparisons so far |
|---|---|---|---|---|---|
| 0 | 1 | 4 | 1 | No | 1 |
| 0 | 2 | 4 | 7 | No | 2 |
| 0 | 3 | 4 | 3 | No | 3 |
| 1 | 2 | 1 | 7 | No | 4 |
| 1 | 3 | 1 | 3 | No | 5 |
| 2 | 3 | 7 | 3 | No | 6 |
No pair is equal, so the method returns false after 6 comparisons.
The second method walks through the array once and keeps every value it has seen in a set. A set answers "have we seen this value?" in a few steps, however many values it holds. If the current value is already in the set, we have a duplicate. If not, we add it.
| Value | In seen? | seen after |
|---|---|---|
| 4 | No | {4} |
| 1 | No | {4, 1} |
| 7 | No | {4, 1, 7} |
| 3 | No | {4, 1, 7, 3} |
This method also returns false, after 4 lookups. Here is the pairs method in code:
Here is the set method:
Go has no set type, so a map from each value to true does the same job.
3 How the count grows
On four values, 6 steps against 4 hardly matters. With n values, the pairs method makes about n²/2 comparisons. The set method does one lookup and one insert per value, so about 2n steps.
| n | Pairs method | Set method |
|---|---|---|
| 10 | 50 | 20 |
| 1,000 | 500,000 | 2,000 |
| 10⁵ | 5 × 10⁹ | 2 × 10⁵ |
When n grows 100 times, the set method does 100 times more work, and the pairs method does 10,000 times more. The way the count grows tells us whether the code survives a large input.
So we tidy a step count down to its growth, with two rules:
- Keep only the biggest term. In 3n + 5 steps, the + 5 hardly matters. At n = 10⁵ it turns 300,000 into 300,005.
- Drop the number in front. 3n and n both grow ten times when n grows ten times, while n² grows a hundred times. The shape matters, not the 3.
The tidy form is Big-O notation. 3n + 5 steps becomes O(n), read "order n", and n²/2 becomes O(n²). So the pairs method is O(n²) and the set method is O(n).
4 The common classes
A few classes cover almost every problem. Here is how each one grows as n grows:
The table puts n = 10⁵ into each and compares the count with about 10⁸ simple steps a second.
| Class | Everyday example | Steps at n = 10⁵ | Verdict |
|---|---|---|---|
| O(1) | Taking the top plate off a stack | 1 | Accepted |
| O(log n) | Finding a word in a dictionary by halving | about 17 | Accepted |
| O(n) | Reading every name on a class register | 10⁵ | Accepted |
| O(n log n) | Sorting a pile of exam papers | about 2 × 10⁶ | Accepted |
| O(n²) | Everyone in a room shaking hands | 10¹⁰ | TLE |
| O(2ⁿ) | Trying every setting of n switches | a 30,000-digit number | TLE |
The term log n is the number of times we can halve n before it reaches 1. At n = 10⁵ it is about 17, and at a million it is only about 20.
The line falls between n log n and n². With n up to 10⁵, O(n log n) finishes well inside a second. O(n²) needs about 100 seconds, far past a limit of one or two seconds.
A third method for Contains Duplicate sits just under the line. It sorts the array so equal values sit side by side, then compares each value with its neighbour. Sorting is O(n log n), so this method gets Accepted too. All three methods are correct. Only their growth separates them.
5 The worst case
The pairs method does not always check every pair. On [4, 4, 7, 3], the first comparison finds the duplicate, so it returns true after one step. On [4, 1, 7, 3], it checks all 6 pairs.
The count we quote is the worst case: the most steps the code can take on any input of size n. For the pairs method, the worst case is an array with no duplicate. It compares every pair, so it is O(n²).
We quote the worst case because the tests include it. A problem that allows 10⁵ values is tested on 10⁵ values with no duplicate, and the pairs method gets TLE there. When someone says O(n²) without naming a case, they mean the worst case.
6 Space: the same idea for memory
A program also uses memory, and we count it the same way. Space complexity is how the extra memory grows with n, on top of the input.
- Pairs method: O(1). It keeps only
iandj, whatever n is. - Set method: O(n). On an array with no duplicate,
seengrows to hold all n values.
The set method buys its speed with memory. Here the trade is a good one. A set of 10⁵ values needs a few megabytes, while 5 × 10⁹ comparisons are far too many.
7 Big-O before code
Once we have an idea for a problem, we work out its Big-O before writing any code. Interviewers ask for it too, right after we explain an approach.
The check takes a minute:
- Find n and the largest n the constraints allow.
- Count how the steps grow with n in the worst case, and keep the biggest term.
- Put the largest n in and compare the result with about 10⁸ steps a second.
- If it is far too many, look for a better idea before coding.
The habit to keep: before writing code, say the idea's time and space in Big-O and check it at the largest n. A correct idea that is too slow still gets TLE.
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.