Counting steps: O(1) and O(n)
After this: Say what O(1) and O(n) mean.
On this page · 8 sections · 3 checks
Programmers often ask how fast a piece of code is. You will hear answers like "this is O(1)" and "that is O(n)". These look like maths, but the idea behind them is small. This lesson explains it, and every later tutorial uses it.
Count steps, not seconds
Measuring a program in seconds does not tell us much. The same code runs faster on a new laptop than on an old phone. So we count something that does not depend on the machine: the number of steps the code takes. A step is one small piece of work, such as reading a cell or comparing two numbers. In these tutorials, the word cost means the number of steps.
The most useful question is this: when the data gets bigger, what happens to the number of steps?
Two jobs on the same array
Take the array [10, 20, 30, 40, 50, 60].
Job 1: read the value at index 3. You saw this in the last lesson. The computer calculates the address and goes there. Other cells do not matter, so the size of the array does not matter either.
Job 2: find out whether 60 is in the array. Now the computer knows a value, not a position. It has no way to calculate where 60 is. So it must look at the cells one at a time, from the start, until it finds 60 or runs out of cells. This is called a .
A scan can be lucky. If the value is in the first cell, one look is enough. It can also be unlucky. If the value is in the last cell, or not in the array at all, every cell must be checked. The unluckiest input is called the . We usually quote the worst case, because it tells you the most work an operation can ever need.
Here is how the two jobs grow.
| Cells in the array | Job 1: read by index | Job 2: scan, worst case |
|---|---|---|
| 10 | same small cost | 10 looks |
| 1,000 | same small cost | 1,000 looks |
| 1,000,000 | same small cost | 1,000,000 looks |
The names: O(1) and O(n)
Programmers use the letter n for the number of items. The two columns of growth above have short names.
- is said "order one" or "constant time". The steps do not grow when the data grows. Reading by index is O(1).
- is said "order n" or "linear time". The steps grow at the same rate as the data. If you double the data, you double the steps. A linear scan is O(n).
These names can be misread in two ways.
- O(1) does not mean exactly one step. Reading a cell took two steps in the last lesson. The 1 means that the count stays the same, however big the array is.
- O(n) does not mean exactly n steps. A job that takes 2n steps, or n + 5 steps, is also O(n), because it grows at the same rate. The notation ignores small differences and looks only at how the work grows.
The code
Here is a linear scan as a function. It looks at one cell each time round the loop, so the worst case is n times round the loop.
def contains(nums, target): for x in nums: # look at each cell in turn if x == target: return True # found it, so stop here return False # looked at every cell, and it is not here
nums = [10, 20, 30, 40, 50, 60]print(contains(nums, 10)) # found on the first lookprint(contains(nums, 60)) # found on the last lookprint(contains(nums, 99)) # not here: every cell was checkedTrue True False
public class Contains { static boolean contains(int[] nums, int target) { for (int x : nums) { // look at each cell in turn if (x == target) { return true; // found it, so stop here } } return false; // looked at every cell, and it is not here }
public static void main(String[] args) { int[] nums = {10, 20, 30, 40, 50, 60}; System.out.println(contains(nums, 10)); // found on the first look System.out.println(contains(nums, 60)); // found on the last look System.out.println(contains(nums, 99)); // not here: every cell was checked }}true true false
Watch it happen
First read a cell by its index. Then search for three values, and compare the comparisons counter.
- Read index 5Read the last cell by its index. The computer goes straight there.
- Search for 10
- Search for 60
- Search for 99
- 010
- 120
- 230
- 340
- 450
- 560
Run an operation to begin.
Check yourself
An array grows from 1,000 values to 1,000,000 values. What happens to the work needed to read the value at index 500?
You scan an array of 2,000 values for a value that is not in it. How many cells do you look at?
A function prints every value in a list once. A list twice as long takes about twice as many steps. Which description fits?
Two more you will meet later
There are two other common names. You do not need to learn them now. This table is here so that you can come back to it.
| Notation | Name | As the data grows | You will meet it in |
|---|---|---|---|
| O(1) | constant | the steps stay the same | reading by index |
| O(log n) | logarithmic | the steps grow very slowly: doubling the data adds about one step | binary search |
| O(n) | linear | the steps grow at the same rate | a linear scan |
| O(n²) | quadratic | double the data, four times the steps | checking every pair of items |
Connect
- Say why we count steps and not seconds.
- Explain O(1): the steps stay the same when the data grows.
- Explain O(n): the steps grow at the same rate as the data.
- Tell the worst case of a linear scan from the lucky case.