Big-O: counting how work grows with input

Video lessonComing soon

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:

ijnums[i]nums[j]Equal?Comparisons so far
0141No1
0247No2
0343No3
1217No4
1313No5
2373No6

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.

ValueIn seen?seen after
4No{4}
1No{4, 1}
7No{4, 1, 7}
3No{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.

nPairs methodSet method
105020
1,000500,0002,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:

n, the input size →steps →O(1)O(log n)O(n)O(n log n)O(n²)O(2ⁿ)
Slow growers stay near the bottom; n² and 2ⁿ shoot off the top

The table puts n = 10⁵ into each and compares the count with about 10⁸ simple steps a second.

ClassEveryday exampleSteps at n = 10⁵Verdict
O(1)Taking the top plate off a stack1Accepted
O(log n)Finding a word in a dictionary by halvingabout 17Accepted
O(n)Reading every name on a class register10⁵Accepted
O(n log n)Sorting a pile of exam papersabout 2 × 10⁶Accepted
O(n²)Everyone in a room shaking hands10¹⁰TLE
O(2ⁿ)Trying every setting of n switchesa 30,000-digit numberTLE

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.

O(1)1O(log n)17O(n)10⁵O(n log n)1.7 × 10⁶O(n²)10¹⁰about 1 second
Steps at n = 10⁵, on a scale where each mark is ten times the last

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 i and j, whatever n is.
  • Set method: O(n). On an array with no duplicate, seen grows 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:

  1. Find n and the largest n the constraints allow.
  2. Count how the steps grow with n in the worst case, and keep the biggest term.
  3. Put the largest n in and compare the result with about 10⁸ steps a second.
  4. 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.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.