A Level Computer Science · Chapter 24 · Component 02: Algorithms and programming
Two correct programs can differ by years in running time on the same data, and Big O notation predicts which one will cope before you ever run it.
This chapter shows how to measure an algorithm by counting its operations, and how Big O notation describes the way that count grows. You will find the complexity of code from its loops, compare growth rates, and see why some problems are beyond any computer.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- explain why algorithms are compared by counting operations rather than timing them
- describe time and space complexity, and the best, average and worst cases
- express a count in Big O notation by keeping its dominant term
- recognise constant, logarithmic, linear, linearithmic, polynomial and exponential complexity
- find the complexity of code from its loops, nested loops, halving loops and recursion
- estimate how running time changes with input size, and the largest input that is feasible
- explain tractable and intractable problems, and why heuristics are used
Time: three sessions, about 4 hours, plus the programming task.
You need first: loops and nested loops from Programming constructs, and the idea of recursion from Subroutines and recursion.
The big picture
The big picture
In 1994, a professor named Thomas Nicely noticed that his computer was dividing some numbers wrongly. The fault was in the hardware, and Intel had to offer to replace its Pentium chips. What he was doing is the more useful story here: running enormous numbers of calculations about prime numbers, a job that took months of computer time.
Speed is usually not about the chip. Two programs that do the same job can differ by a factor of millions, simply because of the method they use. A good algorithm on an old laptop will beat a poor one on a supercomputer, once the data is large enough.
Consider sorting a million names. Bubble sort makes about half a trillion comparisons. Merge sort makes about twenty million. At a billion comparisons a second, bubble sort takes eight minutes and merge sort takes a fiftieth of a second. For a billion names, bubble sort would take about sixteen years, and merge sort about thirty seconds.
So computer scientists need a way to compare algorithms that does not depend on the computer. Timing is not enough, because it changes with the machine, the language and whatever else is running. Instead, we count the basic steps an algorithm takes, as a function of the size of its input.
Big O notation then strips that count down to its essence. It keeps only the part that matters as the input grows, and ignores constant factors. An algorithm is described as O(n), or O(n²), or O(log n), and that one label predicts how it will behave on any amount of data.
This matters in practice. When a website slows down as it gains users, the cause is often an algorithm that was fine for a thousand users but grows too fast for a million. Engineers who can read the complexity of code spot these problems before they happen.
Some problems are so hard that no known algorithm can solve large cases at all. Finding the shortest route through every city on a map is one. For those, we settle for a good answer found quickly, rather than the best answer found never. That idea, the heuristic, closes the chapter.
Section 1
Measuring efficiency
Why not use a stopwatch?
The obvious way to compare two programs is to time them. But a time depends on far more than the algorithm. A faster processor, a different language, a busy operating system or a warm cache can all change it. The same program can run at different speeds on different days.
Timings also say little about larger inputs. A program that takes 2 seconds for 1,000 items might take 4 seconds for 2,000, or 8, or 2,000. The time for one size does not show how it grows.
Common mistake: judging efficiency with a stopwatch alone. A timing measures one program on one machine with one input. It cannot tell you how the time will grow as the data grows. Count the operations as a function of n instead.
A short history
Computer scientists began comparing algorithms formally in the 1960s. Donald Knuth's books, The Art of Computer Programming, set out how to count the steps of an algorithm precisely. Big O notation itself came from mathematics, where it had been used since the 1890s to describe how functions grow.
The ideas matter more as data grows. A program written for a thousand records in 1980 may face a billion today. Its complexity, not the speed of the computer it runs on, decides whether it still works.
Counting operations
Instead, we count operations. An operation is a basic step that takes a roughly fixed time, such as a comparison, an assignment or an arithmetic step. We express the count as a function of n, the size of the input, such as the number of items in a list.
The count need not be exact. Counting every assignment and every comparison is tedious and depends on how the code is written. What matters is how the count grows, so we usually count the step that happens most often, such as a comparison in a sort.
Worked example 1: counting the steps in a loop
Count the operations in this code for a list of n items, and say how the count grows.
total = 0
for i = 0 to n - 1
total = total + items[i]
count = count + 1
next i
average = total / n
| Working | Reason |
|---|---|
| total = 0 runs once, and average = total / n runs once | These lines are outside the loop |
| The two lines inside the loop run n times each | The loop runs once for every item |
| Total: 2n + 2 operations | Add the counts for every line |
| Doubling n roughly doubles the count, so it grows linearly | The 2n term dominates for large n |
Time and space
Time complexity describes how the number of operations grows with n. Space complexity describes how the memory needed grows with n. Both matter. A fast algorithm that needs a copy of a huge data set may be impossible on a device with little memory.
Space is counted in the same way as time. A sort that works within its list, swapping items, uses a fixed amount of extra memory, however long the list is. A sort that copies the list into new arrays needs extra memory in proportion to n.
Counting is an estimate
Counting operations treats every step as taking the same time. In reality, reading from memory can take far longer than an addition, and a cache can make repeated reads faster. So two algorithms with the same count may still differ in speed by a small factor.
That does not spoil the method. Big O is about growth, and these effects change the cost by a constant factor, not by a factor that grows with n. For large inputs, the class of an algorithm decides far more than these details do.
Which operation to count
For a search or a sort, count comparisons between items, because every other step happens at most a fixed number of times per comparison. For arithmetic on numbers, count multiplications. For a program that reads a file, count the records read.
Choosing well makes the analysis simple without making it wrong. If each comparison comes with at most five other steps, the total is at most six times the comparisons. That constant factor disappears in Big O, so counting comparisons alone gives the right class.
What n means
The input size n must be chosen sensibly. For a list, it is the number of items. For a string, it is the number of characters. For a graph, there may be two sizes: the number of nodes and the number of edges. For a number itself, such as testing whether n is prime, it is often the number of digits.
Check yourself. Why is counting operations a fairer way to compare two algorithms than timing them on your own computer?
Show the answer
A count depends only on the algorithm and the size of the input. A timing also depends on the processor, the language and anything else running, so it would change on another computer.
Section 2
Big O notation
Keeping the dominant term
Big O notation describes how a count grows for large n. It keeps only the term that grows fastest, called the dominant term. It also drops any constant factor in front of it. So 3n² + 5n + 2 becomes O(n²), and 2n + 2 becomes O(n).
The reason is that, for large n, the dominant term swamps the rest. At n = 100, the 3n² term of 3n² + 5n + 2 is 30,000, while 5n + 2 is only 502. The leading term is already more than 98% of the total, and its share keeps rising.
Derivation: why lower terms can be dropped
Take a count of the form an² + bn + c. Divide it by its leading term.
As n grows, the fractions b/(an) and c/(an²) shrink towards zero.
So for large n, the whole count behaves like an². The constant a only scales it, and does not change how it grows, so Big O drops it too, giving O(n²).
Common mistake: keeping constants and lower terms in Big O. O(3n² + 5n) and O(n²/2) are not wrong, but they are not in the standard form. Big O describes growth, so write only the dominant term with no constant: O(n²).
Worked example 2: simplifying to Big O
Express 3n² + 5n + 2 in Big O notation, and find what share of the total comes from the leading term when n = 100.
| Working | Reason |
|---|---|
| Terms: 3n², 5n and 2 | Identify every term of the count |
| The fastest-growing term is 3n² | n² grows faster than n or a constant |
| Drop the constant 3: O(n²) | Big O ignores constant factors |
| At n = 100: 30,000 out of 30,502, about 98.4% | The leading term already dominates |
The common classes
A small set of classes covers most algorithms. O(1) is constant time: the work does not depend on n, as in reading one array element. O(log n) is logarithmic: the work grows by one step each time n doubles, as in binary search.
O(n) is linear: the work grows in proportion to n, as in linear search. O(n log n) is linearithmic, the cost of good sorting algorithms such as merge sort. O(n²) is quadratic, as in bubble sort, and O(n³) is cubic. These are polynomial.
O(2ⁿ) is exponential: each extra item doubles the work. Exponential algorithms are only practical for very small n. Some problems are even worse, at O(n!), factorial time.
Common mistake: thinking O(log n) is slower than O(n). A logarithm grows far more slowly than n. For a million items, log₂ n is only about 20. O(log n) is better than O(n), and only O(1) is better still.
Big O as an upper bound
Strictly, Big O gives an upper bound on growth. Saying an algorithm is O(n²) means its cost grows no faster than n², up to a constant factor, for large n. So linear search is technically O(n²) as well, but that would be unhelpful. Always give the tightest class that applies.
Mathematicians also use Ω for a lower bound and Θ when the two meet. In practice, and in this course, Big O is used to mean the tight growth rate. When you write O(n), you mean the cost grows in proportion to n.
Logarithms in Big O
You may wonder which base the logarithm uses. In Big O it does not matter. Logarithms to different bases differ only by a constant factor: log₂ n is about 3.32 times log₁₀ n. Big O drops constant factors, so O(log n) is the same class for every base.
In computing, base 2 is natural, because halving is what algorithms usually do. So log₂ is the one to use when you need an actual count, such as the number of passes of a halving loop.
Classes in everyday software
You meet these classes daily without noticing. Looking up a word in a hash table is O(1) on average. Finding a contact in a sorted list is O(log n). Scrolling through every photo in an album is O(n). Sorting your files by date is O(n log n).
Problems arise when code is accidentally quadratic. A web page that, for each of its n comments, scans every other comment, does n² work. With ten comments that is unnoticeable. With ten thousand comments it is a hundred million steps, and the page freezes.
Order of growth
From best to worst, the order is: O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!). Learn it. Exam questions often ask you to place algorithms in order, or to say which is most efficient for large data.
Check yourself. Write 7n + 4n² + 12 in Big O notation, and explain your choice of term.
Show the answer
It is O(n²). The 4n² term grows fastest, so it dominates for large n. The 7n and 12 terms become negligible, and the constant 4 is dropped.
Section 3
Finding complexity from code
Sequence
Statements that run once each, one after another, take constant time together: O(1). Code made of several parts in sequence takes the time of its slowest part. A loop followed by a nested loop is O(n) + O(n²), which is O(n²).
Single loops
A loop that runs n times, doing a constant amount of work each time, is O(n). The work inside might be several statements, but if their number does not depend on n, the loop is still linear.
Nested loops
When one loop is inside another, the inner loop runs completely for each pass of the outer loop. So their counts multiply. Two nested loops, each running n times, give n × n = n² runs of the inner statement: O(n²).
Common mistake: adding nested loops instead of multiplying. A loop of n inside a loop of n runs n times for each of n passes, which is n², not 2n. Loops one after another add; loops one inside another multiply.
Worked example 3: comparing every pair
A program checks a list of n names for duplicates by comparing each name with every name after it. Find the number of comparisons and the complexity.
for i = 0 to n - 2
for j = i + 1 to n - 1
if names[i] == names[j] then
print("duplicate")
endif
next j
next i
| Working | Reason |
|---|---|
| For i = 0 the inner loop runs n − 1 times, then n − 2, and so on | The inner loop starts just after i |
| Total: (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 | The sum of the first n − 1 whole numbers |
| For n = 1000: 1000 × 999/2 = 499,500 comparisons | Substitute the size of the list |
| n(n − 1)/2 = n²/2 − n/2, which is O(n²) | Keep the dominant term and drop its constant |
Derivation: the number of pairs in a triangular loop
The inner loop runs n − 1 times, then n − 2 times, and so on down to once. Write the sum forwards and backwards.
Adding the two copies term by term gives n − 1 pairs, each adding to n.
The leading term is n²/2. Dropping the constant ½ and the lower term gives O(n²). Starting the inner loop at i + 1 halves the work, but it does not change the class.
Halving loops
Some loops cut the problem in half each time, such as while n > 1, n = n DIV 2. Starting from n, it takes about log₂ n halvings to reach 1. So a halving loop is O(log n). Binary search is the classic example.
Common mistake: thinking a halving loop is O(n). A loop that halves n each time runs only about log₂ n times. For n = 1000 that is 9 passes, not 1000. Look at how the loop variable changes, not just at the fact that there is a loop.
Worked example 4: a halving loop
Count the passes of this loop when n = 1000, and give its complexity.
count = 0
while n > 1
n = n DIV 2
count = count + 1
endwhile
| Working | Reason |
|---|---|
| n takes the values 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1 | DIV 2 halves and rounds down |
| The loop stops when n reaches 1, after 9 passes | Count the halvings before n is 1 |
| ⌊log₂ 1000⌋ = 9, since 2⁹ = 512 ≤ 1000 < 1024 | The pass count is a logarithm |
| Complexity: O(log n) | Doubling n adds only one pass |
Figure 24.2 shows these patterns as dots, one for each run of the innermost statement. Choose a pattern and change n to see how the dots grow. Then switch on the wrong model, which assumes every loop is O(n).
Counting the operations in loops
- Operations counted
- 64
- Complexity
- O(n²)
- At n = 1000
- 1000000
Loops inside loops of different kinds
The rules combine. A halving loop inside a loop of n runs log n times for each of n passes, giving O(n log n). Merge sort has this shape: about log₂ n levels, each doing about n work.
Worked example 5: a loop with a halving loop inside
Find the number of runs of the inner statement, and the complexity, for n = 16.
for i = 1 to n
k = n
while k > 1
k = k DIV 2
steps = steps + 1
endwhile
next i
| Working | Reason |
|---|---|
| The inner while loop runs ⌊log₂ 16⌋ = 4 times | It halves k from 16 down to 1 |
| The outer loop runs 16 times | Once for each value of i |
| Total: 16 × 4 = 64 runs | Nested loops multiply their counts |
| In general n × log₂ n, which is O(n log n) | Linear outer loop times logarithmic inner loop |
Loops that stop early
Some loops can finish before they reach n, such as a search that returns as soon as it finds its target. For these, count the worst case, when the loop runs all the way. An early exit improves the best and average cases, but it does not change the worst-case class.
Loops can also run a fixed number of times, such as for i = 1 to 10. That costs a constant, however large n is, so the loop adds only O(1). Only loops whose length depends on n change the class.
Reading complexity at a glance
With practice, you can read complexity from the shape of code. Look for loops and ask how many times each runs, in terms of n. Note which loops are inside others. Look for anything that halves or doubles. Then combine: multiply for nesting, add for sequence, and keep the largest term.
Beware of hidden loops. A single line such as a call to a sort function, or a search for an item in a list, may itself be O(n log n) or O(n). A loop that calls such a function on every pass multiplies their costs together.
Recursion
For a recursive function, count the calls and the work in each call. A function that calls itself once on n − 1 makes n calls: O(n). Binary search calls itself once on half the list: O(log n). A function that calls itself twice on n − 1 can double its calls at every level: O(2ⁿ).
Check yourself. A program runs a loop of n, then, separately, two nested loops of n. What is its complexity?
Show the answer
The parts run one after another, so their costs add: O(n) + O(n²). For large n the n² part dominates, so the whole program is O(n²).
Section 4
Best, average and worst cases
The three cases
The work an algorithm does can depend on the data, not just its size. Linear search finds a target at the front in one comparison, but needs n if the target is last. So we describe three cases: the best, the average and the worst.
The best case is the least work for any input of size n. The worst case is the most. The average case is the expected work over typical inputs, which needs an assumption about what is typical.
Why the worst case is quoted
When an algorithm's complexity is given without saying which case, it usually means the worst case. The worst case is a guarantee: the algorithm will never be slower than this. That matters when a system must respond in time, such as a car's braking software.
Common mistake: describing an algorithm by its best case. Bubble sort is O(n) on sorted data, but that says little about its usual behaviour. Quoting the best case hides how slow an algorithm can be. State the worst case unless the question asks for another.
Worked example 6: the cases of linear search
Give the best, average and worst cases of linear search on n items, in comparisons and in Big O.
| Working | Reason |
|---|---|
| Best: the target is first, so 1 comparison, O(1) | The loop stops at the first item |
| Worst: the target is last or absent, so n comparisons, O(n) | Every item must be checked |
| Average: about (n + 1)/2 comparisons, O(n) | A present target is equally likely anywhere |
| Quoted complexity: O(n) | The worst case is the usual guarantee |
The average case here has the same Big O as the worst case, because n/2 and n differ only by a constant. That is common. But quick sort is an exception: its average is O(n log n) and its worst case is O(n²).
Space complexity
Space complexity counts the extra memory an algorithm needs beyond its input. An in-place algorithm, such as bubble sort, needs only a few variables: O(1). Merge sort copies items into new lists as it merges: O(n).
Recursion uses memory too. Each call that has not yet returned keeps its local variables and return address on the call stack. A recursive function that goes n calls deep needs O(n) stack space, even if it stores nothing else.
Common mistake: forgetting that recursion uses memory. A recursive function looks as if it stores nothing, but every unfinished call sits on the stack. A recursion n levels deep uses O(n) memory, and a very deep one can overflow the stack and crash.
Worked example 7: comparing space
Compare the extra memory needed by bubble sort, merge sort and recursive binary search on n items.
| Working | Reason |
|---|---|
| Bubble sort swaps within the list, using a temporary variable | Only a fixed number of extra variables, O(1) |
| Merge sort writes merged items into new lists | Extra space grows with the list, O(n) |
| Recursive binary search goes about log₂ n calls deep | Each waiting call uses stack space, O(log n) |
| Iterative binary search uses only low, high and mid | A loop needs no stack of calls, O(1) |
Average cases need assumptions
Working out an average case needs a picture of typical inputs. For linear search we assumed the target is equally likely to be anywhere. If most searches are for recent items stored at the front, the real average is far better. If most targets are absent, it is far worse.
That is why the average case is less often quoted. It is only as good as the assumption behind it. The worst case needs no assumption at all, which makes it the safer basis for a promise about performance.
Trading space for time
Sometimes using more memory saves time. Checking a list for duplicates by comparing every pair is O(n²) time and O(1) space. Putting each item into a hash table as you go, and checking whether it is already there, is O(n) time but O(n) space. Which is better depends on whether time or memory is scarcer.
Check yourself. Why does quoting an algorithm's worst case give a more useful guarantee than its average case?
Show the answer
The worst case is an upper limit that holds for every input of that size, so the algorithm can never be slower. The average depends on assumptions about the data, which may not hold.
Section 5
Comparing growth rates
What doubling does
A quick way to feel a complexity class is to double n. For O(n), the work doubles. For O(n²), it quadruples, because (2n)² = 4n². For O(n³), it goes up eight times. For O(log n), it rises by just one step.
For O(2ⁿ), doubling n squares the work, because 2²ⁿ = (2ⁿ)². Even adding one item doubles it. This is why exponential algorithms become hopeless so quickly.
Common mistake: assuming doubling the input doubles the time. That is true only for O(n). An O(n²) algorithm takes four times as long on twice the data, and an O(2ⁿ) algorithm far longer. Work out the ratio from the complexity class.
Figure 24.1 shows each class at n and at 2n. Move n and compare how far each outline stretches beyond its bar. Then switch on the wrong model, which assumes every class simply doubles.
What doubling the input does
- O(n²) when n doubles
- × 4
- O(2ⁿ) when n doubles
- × 1024
- O(2ⁿ) at 2n, 10⁹ operations a second
- 0 s
Estimating running times
If you know the time for one input size, Big O lets you estimate the time for another. Multiply the known time by the ratio of the growth function at the two sizes. This assumes the constant factors stay the same, which is reasonable on the same machine.
Worked example 8: scaling a time
An O(n log n) sort takes 1 second for 1,024 items. Estimate its time for 4,096 items.
| Working | Reason |
|---|---|
| At n = 1024: 1024 × log₂ 1024 = 1024 × 10 = 10,240 | Growth function at the measured size |
| At n = 4096: 4096 × 12 = 49,152 | Growth function at the new size |
| Ratio: 49,152 ÷ 10,240 = 4.8 | How many times more work there is |
| Estimate: 1 × 4.8 = 4.8 seconds | Scale the measured time by the ratio |
Notice that four times the data took 4.8 times as long, a little more than linear. An O(n²) sort would have taken 16 times as long, and an O(2ⁿ) one would never finish.
Feasible input sizes
Another way to compare classes is to ask how large an input each can handle in a fixed time. Suppose a computer performs 10⁹ operations a second. In one second, an O(n) algorithm can handle a billion items, an O(n²) one about 31,000, and an O(2ⁿ) one only about 29.
Worked example 9: the largest feasible input
At 10⁹ operations a second, find the largest n an O(n²) algorithm and an O(2ⁿ) algorithm can handle in one second.
| Working | Reason |
|---|---|
| O(n²): n² ≤ 10⁹, so n ≤ √10⁹ ≈ 31,622 | Solve for the largest whole n |
| O(2ⁿ): 2ⁿ ≤ 10⁹, so n ≤ log₂ 10⁹ ≈ 29.9 | Take logarithms to solve |
| The largest whole n is 29, since 2³⁰ is just over 10⁹ | Round down to stay within the budget |
| A thousand times faster computer adds only about 10 to n for O(2ⁿ) | Because two to the ten is about a thousand |
Logarithmic and linearithmic in practice
The difference between O(n) and O(n log n) is small in practice. For a million items, log₂ n is only about 20, so an O(n log n) algorithm does about twenty times the work of an O(n) one. That is why O(n log n) sorting is fast enough for almost any data a single computer holds.
The difference between O(n log n) and O(n²) is enormous. For a million items, it is a factor of about fifty thousand. Moving from a quadratic algorithm to a linearithmic one is often the single biggest improvement a programmer can make.
Constants still matter for small n
Big O describes large inputs. For small inputs, constant factors can win. An O(n²) algorithm costing n² steps beats an O(n) algorithm costing 100n steps for every n up to 100. That is why fast library sorts switch to insertion sort for very short lists.
Worked example 10: a crossover point
Algorithm A takes n² steps and algorithm B takes 100n steps. Find the smallest n at which A is slower than B.
| Working | Reason |
|---|---|
| A is slower when n² > 100n | Compare the two step counts |
| Divide both sides by n: n > 100 | n is positive, so the inequality holds |
| The smallest whole n is 101 | At n = 100 the two are equal |
| Below 101, the O(n²) algorithm is actually faster | Constant factors win for small inputs |
Common mistake: judging algorithms on tiny inputs. On ten items, almost any algorithm is instant, and the one with the smaller constant may even win. Complexity is about how the cost grows, so compare algorithms on the sizes they will really face.
Check yourself. Taking 5 seconds for 100 items, how long would an O(n³) algorithm need for 300 items?
Show the answer
The input is 3 times larger, and for O(n³) the work grows by 3³ = 27. So the estimate is 5 × 27 = 135 seconds.
Section 6
Tractable and intractable problems
Why the line is drawn at polynomials
Polynomial algorithms scale gracefully. Suppose a computer becomes twice as fast. In the same time, an O(n²) algorithm can then handle about 1.4 times as much data, and an O(n³) one about 1.26 times as much. The gains are modest but real, and they keep coming as hardware improves.
Exponential algorithms do not scale. Twice the speed buys just one more item for O(2ⁿ). That difference in behaviour is why the boundary between tractable and intractable is drawn between polynomial and exponential time.
Tractable problems
A problem is tractable if it can be solved in polynomial time, such as O(n), O(n²) or O(n³). Polynomial algorithms can handle large inputs with enough computing power. Searching, sorting and finding shortest paths are all tractable.
Intractable problems
A problem is intractable if no polynomial-time algorithm is known for it. The best known algorithms are exponential or worse. For small inputs they work, but the time explodes as the input grows. No foreseeable computer can solve large cases exactly.
The travelling salesperson problem is the famous example. Given a set of cities, find the shortest route that visits each once and returns to the start. Checking every route works, but with c cities there are (c − 1)!/2 routes to check.
Worked example 11: counting routes
A delivery driver must visit 10 locations and return to the depot. Find the number of distinct routes a brute-force search checks, and compare with 20 locations.
| Working | Reason |
|---|---|
| Fix the starting location: (10 − 1)! orders remain | Every route can start at the same place |
| Each route and its reverse have the same length: divide by 2 | A route driven backwards is the same route |
| 9!/2 = 362,880/2 = 181,440 routes | Easily checked by a computer |
| For 20 locations: 19!/2 ≈ 6.1 × 10¹⁶ routes | At 10⁹ a second, about two years of checking |
Exponential growth in a familiar function
Exponential growth can hide in simple code. The recursive Fibonacci function, fib(n) = fib(n − 1) + fib(n − 2), calls itself twice at each level. It recomputes the same values over and over, and fib(30) makes over 2.6 million calls. An iterative loop computes the same value in 30 steps.
Heuristics
For intractable problems, we use heuristics. A heuristic is a rule of thumb that finds a good solution quickly, without guaranteeing the best one. For the travelling salesperson, "always drive to the nearest unvisited location" gives a decent route in O(n²) time.
Common mistake: assuming a heuristic gives the best answer. A heuristic trades certainty for speed. The nearest-neighbour route is usually good but can be well over the shortest possible. Say that a heuristic gives an acceptable answer, not the optimal one.
Real solvers
In practice, delivery firms and chip designers solve large travelling salesperson problems every day. They use clever exact methods that prune away hopeless routes, plus heuristics that improve a route by swapping pairs of stops. Routes for thousands of stops can be found within a fraction of a percent of the best.
These methods are still exponential in the worst case. They work because real maps are not the worst case. That is an important lesson: worst-case analysis tells you what is guaranteed, but real data is often kinder.
Faster computers do not help
A faster computer cannot rescue an exponential algorithm. If a computer becomes 1,000 times faster, an O(2ⁿ) algorithm can handle only about 10 more items in the same time. An O(n) algorithm, by contrast, could handle 1,000 times more.
Common mistake: thinking a faster computer fixes an intractable problem. Exponential growth outruns any speed-up. Each extra item doubles the work, so even a computer a million times faster gains only about twenty items. A better algorithm, or a heuristic, is the only real fix.
P and NP
Computer scientists group problems by the time their best algorithms need. The class P holds problems that can be solved in polynomial time. The class NP holds problems whose answers can be checked in polynomial time, even if finding them seems to take longer.
The travelling salesperson problem, in its yes-or-no form, is in NP: given a route, checking its length is quick. Nobody knows whether every NP problem is also in P. It is one of the great open questions in mathematics, with a prize of a million dollars for a proof either way.
Problems with no algorithm at all
Some problems are worse than intractable: they are unsolvable. Alan Turing proved in 1936 that no algorithm can decide, for every program and input, whether the program will eventually stop. This halting problem shows that there are limits to computation itself, not just to speed.
Check yourself. Why is the brute-force solution to the travelling salesperson problem described as intractable?
Show the answer
The number of routes to check grows factorially, as (c − 1)!/2, which is faster than any polynomial. Even modest numbers of cities give too many routes for any computer to check in a reasonable time.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Time complexity | How the operation count grows with n | Linear search, O(n) | Count the most frequent step |
| Space complexity | How the extra memory grows with n | Merge sort, O(n) | Recursion uses stack space |
| Big O notation | The dominant term, with constants dropped | 3n² + 5n + 2 is O(n²) | Keep only the fastest-growing term |
| O(1) and O(log n) | Constant, and one step more per doubling | Array access; binary search | log₂ of a million is about 20 |
| O(n) and O(n log n) | Linear, and linear times a logarithm | Linear search; merge sort | The best general sorts are O(n log n) |
| O(n²) and O(n³) | Quadratic and cubic: polynomial | Nested loops; bubble sort | Doubling n multiplies by 4 or 8 |
| O(2ⁿ) | Exponential | Naive recursive Fibonacci | One more item doubles the work |
| Best, average, worst | Least, typical and most work for size n | Linear search: 1, about n/2, n | Quote the worst case as a guarantee |
| Tractable and intractable | Polynomial time, or no polynomial algorithm known | Sorting; travelling salesperson | Intractable problems use heuristics |
Programming task
Programming task: counting operations
Aim
Write Python functions that count the runs of the inner statement for four loop patterns, then print a table of counts as n doubles. Use the table to confirm the growth ratios predicted by Big O.
Design
Each function takes n and returns a count. Each one contains the loop pattern it measures, with a counter incremented by the innermost statement. A main loop calls every function for n = 100, 200, 400 and 800, and prints the counts and the ratio between successive rows.
The tests check each function against a count worked out by hand. Edge cases, such as n = 0 and n = 1, check that the loops run zero times when they should.
Code
def count_single(n):
count = 0
for i in range(n):
count += 1
return count
def count_nested(n):
count = 0
for i in range(n):
for j in range(n):
count += 1
return count
def count_triangular(n):
count = 0
for i in range(n):
for j in range(i + 1, n):
count += 1
return count
def count_halving(n):
count = 0
while n > 1:
n //= 2
count += 1
return count
previous = None
for n in [100, 200, 400, 800]:
row = [f(n) for f in (count_single, count_nested, count_triangular, count_halving)]
ratios = [round(a / b, 2) for a, b in zip(row, previous)] if previous else []
print(n, row, ratios)
previous = row
Each doubling of n should double the single count, multiply the nested and triangular counts by about 4, and add 1 to the halving count. The printed ratios let you check this directly, which is a practical test of the theory.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | count_single(10) | 10 | One run per item |
| 2 | count_nested(10) | 100 | Nested loops multiply: 10 × 10 |
| 3 | count_triangular(10) | 45 | 10 × 9/2 pairs |
| 4 | count_halving(1000) | 9 | Matches worked example 4 |
| 5 | count_halving(1) | 0 | The loop must not run at all |
| 6 | count_nested(0) | 0 | An empty input does no work |
| 7 | count_nested(200) / count_nested(100) | 4.0 | Doubling n quadruples O(n²) work |
Evaluation
The counts match the formulas exactly, and the ratios confirm the predictions of Big O: 2 for linear, about 4 for quadratic, and an increase of 1 for logarithmic. Counting is reliable because it does not depend on the speed of the computer.
An improvement would also time each function with time.perf_counter and compare the timings with the counts. The timings will be noisier, which shows why counting is preferred for analysis.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Put these complexity classes in order from most to least efficient: O(n²), O(1), O(n log n), O(2ⁿ), O(log n), O(n).
Worked solution to Q1
From most to least efficient the order is O(1), O(log n), O(n), O(n log n), O(n²), O(2ⁿ). Each class grows faster than the one before it for large n.
Q2. State what is meant by the space complexity of an algorithm.
Worked solution to Q2
Space complexity describes how the extra memory an algorithm needs grows as the size of its input grows. It counts working memory beyond the input itself, including stack space for recursion.
Q3. Name one tractable problem and one intractable problem.
Worked solution to Q3
Sorting a list is tractable, because merge sort solves it in O(n log n), which is polynomial. The travelling salesperson problem is intractable, because no polynomial-time algorithm for it is known.
Rung 2: Application
Q4. Express 5n³ + 20n² + 100n + 7 in Big O notation, and give a reason.
Worked solution to Q4
The n³ term grows fastest, so it dominates as n becomes large. Dropping the lower terms and the constant 5 gives O(n³).
Q5. A loop runs from 1 to n, and inside it a second loop runs from 1 to 10. Give the complexity of the code.
Worked solution to Q5
The inner loop always runs 10 times, whatever n is, so each outer pass costs a constant. The total is 10n operations, which is O(n). Only loops that depend on n change the class.
Q6. How many comparisons does the duplicate check in worked example 3 make for a list of 50 names?
Worked solution to Q6
The check compares each name with every name after it, which is n(n − 1)/2 comparisons. With n = 50, that is 50 × 49/2 = 1,225 comparisons. The count grows as O(n²), so doubling the list would roughly quadruple it.
Q7. A program takes 4 seconds for 1,000 items and is O(n). Estimate its time for 5,000 items.
Worked solution to Q7
For O(n), the time grows in proportion to n. Five times the data takes five times as long, so the estimate is 4 × 5 = 20 seconds.
Rung 3: Analysis
Q8. Estimate the time for 10,000 items of an O(n²) algorithm that takes 3 seconds for 2,000 items.
Worked solution to Q8
The input is 5 times larger, and for O(n²) the time grows by the square of that factor, 5² = 25. So the estimate is 3 × 25 = 75 seconds.
Q9. Algorithm A takes 4n³ steps and algorithm B takes 500n² steps. Find the smallest whole n at which A becomes slower.
Worked solution to Q9
A is slower when 4n³ > 500n². Dividing both sides by 4n² gives n > 125. At n = 125 the two are equal, so the smallest whole n at which A is slower is 126.
Q10. Explain why the recursive Fibonacci function fib(5) makes 15 calls, and why the count grows exponentially.
Worked solution to Q10
Each call to fib(k) with k ≥ 2 makes two more calls, to fib(k − 1) and fib(k − 2). The counts add as 1, 1, 3, 5, 9, 15 for n = 0 to 5. Each step roughly multiplies the calls by about 1.6, so the total grows exponentially.
Q11. At 10⁹ operations a second, how many items can an O(n log n) algorithm process in one second, roughly?
Worked solution to Q11
We need n log₂ n ≤ 10⁹. Trying n = 4 × 10⁷ gives about 4 × 10⁷ × 25 = 10⁹. So it can process roughly 40 million items, far more than the 31,000 of an O(n²) algorithm.
Rung 4: Stretch
Q12. A computer becomes 1,000 times faster. Estimate how many more items an O(2ⁿ) algorithm can then handle in the same time, and explain.
Worked solution to Q12
With 1,000 times the speed, the algorithm can do 1,000 times as many operations. Each extra item doubles the work, and 2¹⁰ = 1,024 ≈ 1,000. So it gains only about 10 items, however large n already was.
Q13. Compare the time and space complexity of checking for duplicates by comparing every pair with using a hash table.
Worked solution to Q13
Comparing every pair takes O(n²) time but only O(1) extra space. Using a hash table checks each item once, in O(n) time on average, but stores up to n items, so it needs O(n) space. The hash table trades memory for speed.
Q14. Explain why an O(n log n) algorithm with a large constant factor may still be the right choice over an O(n²) algorithm for a database of a million records.
Worked solution to Q14
For a million records, n log₂ n is about 2 × 10⁷, but n² is 10¹², fifty thousand times more. Even if the O(n log n) algorithm's constant is a hundred times larger, it still does about five hundred times less work. Constants matter only for small inputs.
Exam practice
Exam technique and worked answer workshop
Complexity questions reward reasoning, not just labels. Say why code has a given complexity: "the inner loop runs n times for each of the n passes of the outer loop, so n² in total". A bare O(n²) earns less than the reasoning that leads to it.
For estimates, show the ratio. Write the growth function at both sizes, divide, then multiply the known time. Examiners award method marks for each step, so a slip in arithmetic still leaves most of the marks.
In discussion questions, use the right vocabulary. Tractable means polynomial time; intractable means no polynomial algorithm is known. Heuristics give good, not optimal, answers. Link your points to the context, such as a delivery company or a website.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
Code fragment A has a single loop from 1 to n. Fragment B has a loop from 1 to n with a second loop from 1 to n inside it. Fragment C has a loop that halves n until it reaches 1.
(a) Give the time complexity of each fragment in Big O notation. [3]
(b) State which fragment is most efficient for large n. [1]
Mark scheme for exam question 1
- B1 A is O(n)
- B1 B is O(n²)
- B1 C is O(log n)
- B1 C is the most efficient for large n
Exam question 2 (5 marks · Paper 02 · about 6 minutes)
An algorithm makes 4n³ + 2n² + 100 operations for an input of size n.
(a) State its time complexity in Big O notation. [1]
(b) Explain why the terms 2n² and 100 can be ignored. [2]
(c) A second algorithm makes 500n² operations. Find the smallest whole n for which the first algorithm makes more operations. [2]
Mark scheme for exam question 2
- B1 O(n³)
- B1 for large n, the n³ term grows much faster than the other terms
- B1 so the other terms become a negligible share of the total
- M1 solve 4n³ > 500n², giving n > 125
- A1 126
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
An algorithm processes 2,000 records in 3 seconds.
(a) The algorithm is O(n²). Estimate the time for 10,000 records. [2]
(b) A second algorithm is O(n log n) and also takes 3 seconds for 2,000 records. Estimate its time for 10,000 records, showing your working. [3]
Mark scheme for exam question 3
- M1 the ratio of sizes is 5, so the time grows by 5² = 25
- A1 75 seconds
- M1 10,000 × log₂ 10,000 compared with 2,000 × log₂ 2,000
- M1 the ratio is about 132,877 ÷ 21,932, which is about 6.06
- A1 about 18.2 seconds
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
(a) State the best-case and worst-case time complexities of linear search and of binary search. [4]
(b) Explain why the worst case is usually quoted when comparing algorithms. [1]
Mark scheme for exam question 4
- B1 linear search best case O(1)
- B1 linear search worst case O(n)
- B1 binary search best case O(1)
- B1 binary search worst case O(log n)
- B1 the worst case is a guarantee: the algorithm is never slower than this for any input
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A delivery company plans a route for each van, visiting up to 25 addresses and returning to the depot. Discuss whether it should find the shortest route by checking every possible route, or use a heuristic.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear explanation that checking every route is intractable, with the number of routes or its growth stated. The answer explains what a heuristic is and how one would work here. It weighs the cost of a slightly longer route against the time saved, and reaches a justified recommendation.
Level 2 (3–4 marks): a correct explanation of why brute force is impractical, with some discussion of heuristics. The weighing of the two approaches, or the recommendation, is limited.
Level 1 (1–2 marks): some relevant points, such as that there are many routes or that a heuristic is quicker, with little explanation. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- this is the travelling salesperson problem, which is intractable
- with c addresses there are (c − 1)!/2 routes; for 25 that is about 3 × 10²³
- even at 10⁹ routes a second, checking them all would take millions of years
- a faster computer would barely help, because the growth is factorial
- a heuristic such as nearest neighbour builds a route in O(n²) time
- a heuristic gives a good route quickly, but not necessarily the shortest
- the route must be ready each morning, so speed matters more than perfection
- recommendation: use a heuristic, perhaps improved by local adjustments
Annotated model answer: exam question 5
"Finding the shortest route that visits every address and returns is the travelling salesperson problem. With c addresses, there are (c − 1)!/2 different routes. For 25 addresses, that is 24!/2, about 3 × 10²³ routes." (The problem named, with the scale of brute force.)
"Even checking a billion routes a second, this would take millions of years. A faster computer would not help, because adding one more address multiplies the number of routes again. The problem is intractable." (Why brute force fails.)
"A heuristic finds a good route quickly without guaranteeing the best. For example, the nearest-neighbour rule always drives next to the closest unvisited address. It builds a route in O(n²) time, which takes a fraction of a second." (How a heuristic works here.)
"The route might be a little longer than the best possible, costing some fuel. But the company needs routes every morning, so a good route now is worth far more than a perfect one never. It should use a heuristic." (Weighing the trade-off, and a justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It quantifies the problem, explains the alternative and makes a clear judgement.
Exam question 6 (5 marks · Paper 02 · about 7 minutes)
(a) Write a function hasDuplicate(items) that returns True if any value appears more than once, by comparing every pair of items. [3]
(b) State the time complexity of your function, and describe a faster approach and its cost. [2]
Mark scheme for exam question 6
- B1 an outer loop over every index i
- B1 an inner loop over every index j after i
- B1 True returned when items[i] == items[j], and False after both loops finish
- B1 O(n²), because the nested loops compare every pair
- B1 a hash table or set gives O(n) time, but needs O(n) extra space
Annotated model answer: exam question 6
function hasDuplicate(items)
for i = 0 to items.length - 2
for j = i + 1 to items.length - 1
if items[i] == items[j] then
return True
endif
next j
next i
return False
endfunction
The outer loop over i and the inner loop from i + 1 earn the first two marks. Returning True on a match, and False only after both loops, earns the third. The nested loops compare every pair, so the function is O(n²). Adding each item to a set and checking whether it is already there is O(n) on average, at the cost of O(n) space.
Exam question 7 (5 marks · Paper 02 · about 7 minutes)
The function fib(n) returns n if n is 0 or 1, and otherwise returns fib(n − 1) + fib(n − 2).
(a) State how many calls are made in total when fib(5) is called. [1]
(b) Explain why the time complexity of this function is exponential. [2]
(c) Describe an iterative approach and give its time complexity. [2]
Mark scheme for exam question 7
- B1 15 calls
- B1 each call with n ≥ 2 makes two further calls
- B1 the same values are recomputed many times, so the number of calls grows exponentially with n
- B1 keep the last two values in variables and loop from 2 up to n, adding them
- B1 O(n)
Exam question 8 (5 marks · Paper 01 · about 7 minutes)
An embedded controller has very little memory. It must sort lists of up to 10,000 readings.
(a) Compare the space complexity of bubble sort and merge sort. [2]
(b) Explain why a recursive algorithm can use more memory than an iterative one that does the same job. [2]
(c) Recommend a sort for this controller. [1]
Mark scheme for exam question 8
- B1 bubble sort works in place, needing O(1) extra space
- B1 merge sort needs O(n) extra space for the merged lists
- B1 each unfinished recursive call keeps its data and return address on the stack
- B1 so a recursion n levels deep needs O(n) stack space, which a loop does not
- B1 an in-place sort such as insertion sort or bubble sort, because memory is the constraint
Connections
Synoptic link
Every algorithm in the course can be analysed with these tools. Searching and sorting algorithms applies them to the standard searches and sorts, explaining why binary search is O(log n) and merge sort is O(n log n). Graph traversal and shortest paths uses them for Dijkstra's algorithm and A*.
Recursion's memory cost comes from the call stack, described in Arrays, records, stacks and queues and in Subroutines and recursion. Heuristics for intractable problems connect to Computational thinking, where abstraction and approximation help tame hard problems.
Synoptic question 1. A sorted list of n items is searched m times. Using worst cases, find the total comparisons for binary search when n = 1,000,000 and m = 1,000, and compare with linear search.
Answer to synoptic question 1
Binary search needs at most ⌊log₂ 1,000,000⌋ + 1 = 20 comparisons per search, so 1,000 searches need about 20,000. Linear search needs up to 1,000,000 per search, so 1,000,000,000 in total. Binary search does fifty thousand times less work.
Recap
Recap and next step
- Algorithms are compared by counting operations as a function of the input size n, not by timing them.
- Big O notation keeps only the dominant term and drops constants: 3n² + 5n + 2 is O(n²).
- From best to worst: O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ).
- Loops in sequence add; nested loops multiply; a halving loop is O(log n).
- Best, average and worst cases describe how the data affects the work; the worst case is the usual guarantee, and space complexity counts extra memory, including recursion.
- Doubling n doubles O(n) work, quadruples O(n²) work and squares O(2ⁿ) work; Big O lets you scale measured times.
- Tractable problems have polynomial algorithms; intractable ones do not, so heuristics give good answers quickly.
Next chapter: Searching and sorting algorithms applies this analysis to linear and binary search and to bubble, insertion, merge and quick sort.
For your exam board
OCR A Level Computer Science (H446): this chapter covers the analysis and comparison of algorithms in section 2.3.1, Algorithms, in Component 02, Algorithms and programming: time and space complexity, best, average and worst cases, and Big O notation for constant, linear, polynomial, exponential and logarithmic complexity. Heuristics link to section 2.2.2, Computational methods.
AQA A Level Computer Science (7517): comparing algorithms, Big O notation, orders of complexity, and tractable and intractable problems, including the halting problem and heuristics, appear in the theory of computation section, assessed on Paper 1.