A Level Computer Science · Chapter 27 · Component 02: Algorithms and programming
The algorithms paper rewards a method: read the scenario, choose the data structures and algorithm, write clear pseudocode, then trace and improve it.
This chapter brings together the whole of the algorithms and programming course and turns it into a method for unfamiliar problems. It teaches how to read a scenario, choose data structures and algorithms, write algorithms from common patterns, trace and debug given code, and evaluate and improve a solution.
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:
- break a scenario down into its inputs, outputs, data and constraints before writing any code
- choose a suitable data structure for each part of a problem and justify the choice
- compare algorithms for a task by counting their operations, and find when one overtakes another
- write algorithms in pseudocode using the patterns of counting, totalling, finding a maximum, searching, validating and two pointers
- trace given code with a trace table, and find and correct errors in it
- evaluate a solution for efficiency, memory, readability and correctness, and improve it
Time: three sessions, about 4 hours, plus the programming task.
You need first: every earlier chapter of the algorithms and programming course, especially Computational thinking, Searching and sorting algorithms and Algorithm analysis and Big O notation.
The big picture
The big picture
The algorithms paper is different from a test of recall. Its longest questions describe a situation you have never seen, such as a car park, a card game or a delivery firm. They ask you to solve a problem within it. There is no single answer to memorise. What earns the marks is a sound method, applied step by step, with each step shown clearly enough for an examiner to follow.
Strong candidates do not start by writing code. They start by understanding the problem. What is the program given? What must it produce? What data must it remember between steps? What limits are there on the values? Answering these questions first turns a long paragraph of scenario into a short list of precise requirements. Those requirements then guide every later choice.
The method has six stages. Read the scenario carefully, marking the key facts. Identify the inputs, outputs, stored data and constraints. Choose the data structures and the algorithm. Write the solution in clear pseudocode, using patterns you know. Trace it with a small example to check it works. Then evaluate and improve it, considering its efficiency and its weaknesses.
Each stage draws on earlier chapters. Identifying inputs and outputs is thinking ahead, from Computational thinking. Choosing a structure uses the stacks, queues, hash tables and trees of the data structures chapters. Choosing an algorithm uses the searches, sorts and graph algorithms, with Big O to compare them. Writing and tracing use the programming constructs and subroutines. Evaluating uses testing and performance modelling.
The paper also contains shorter questions that test one stage at a time. Some give a piece of code and ask what it outputs, or ask you to find an error. Some ask you to complete a partly written algorithm. Others ask which algorithm suits a task and why. The method in this chapter helps with all of them, because each short question is one stage of the long one.
The questions in a long scenario usually build on each other. An early part may ask you to describe a structure, and a later part to write an algorithm that uses it. A final part may ask you to evaluate or improve that algorithm. Reading every part before starting the first shows where the question is heading. It also stops you making an early choice that a later part makes awkward.
Time matters too. A long scenario question may carry a quarter of the paper's marks, so it deserves a quarter of the time. Spending five minutes understanding the problem saves far more than five minutes of wasted writing later. A clear plan also earns marks of its own, because examiners give credit for a correct method even when the final answer is not quite right.
Section 1
Reading a scenario
Inputs, outputs, data and constraints
Every scenario hides the same four things. The inputs are what the program is given, by a user, a file or a sensor. The outputs are what it must produce. The stored data is what it must remember, often for a long time, such as a list of members or the state of a game board. The constraints are the rules and limits, such as "a member may book at most two courts a day".
Writing these down first has two benefits. It makes sure you solve the problem actually set, rather than one you imagined. And it exposes questions the scenario leaves open, such as what should happen when a court is already booked. Where the scenario does not say, state a sensible assumption and carry on.
Common mistake: thinking you should start writing code before working out the inputs and outputs. Code written too early solves whatever problem the writer had in mind, not the one set. Listing inputs, outputs, stored data and constraints first takes minutes, and it stops whole answers going the wrong way.
A scenario can also be broken down into the tasks the program performs. The car park program must admit a car, charge a car on exit and report the number of free spaces. Each task becomes a subroutine, with its own inputs and outputs taken from the breakdown. The structure of the answer then follows the structure of the problem.
Worked example 1: a car park
A car park has 200 spaces. Cars are charged £2 for each hour or part of an hour, up to £15 a day. Break the scenario down and find the charge for a stay of 3 hours 10 minutes.
| Working | Reason |
|---|---|
| Inputs: registration and time at entry and at exit | These arrive from the barrier cameras |
| Stored: each car inside with its entry time, and free spaces | Needed when the car leaves later |
| 3 hours 10 minutes counts as 4 hours | Any part of an hour is charged in full |
| Charge = 4 × £2 = £8, below the £15 limit | The daily cap does not apply here |
Worked example 2: stating an assumption
The scenario does not say what happens when a car stays past midnight. State a sensible assumption and how the program would apply it.
| Working | Reason |
|---|---|
| Assume each calendar day is capped separately at £15 | A common and fair rule for car parks |
| Split the stay at each midnight into separate days | So each day's charge can be capped |
| Charge each day by its hours, capped at £15 | Applies the scenario's rule to every day |
| Write the assumption at the start of the answer | The examiner can then follow the logic |
Reading actively
Read the scenario twice. The first time, read it straight through to get the overall picture. The second time, underline every number, every rule and every word such as "only", "at most" or "unless". Those words become conditions in the code, and missing one is the commonest way to lose marks on a long question.
Each constraint usually becomes a check somewhere in the solution. "Up to 20 places" becomes a comparison before a booking is accepted. "At most two courts a day" becomes a count of the member's bookings for that day. Turning each constraint into a named check, written down beside the requirement it comes from, makes it easy to show that nothing has been missed.
Abstraction in a scenario
A scenario always contains details that do not matter to the program. The colour of the barrier, the name of the car park's owner and the weather are there to make the story real. Abstraction means ignoring them. Underlining the facts that change the answer, such as numbers, limits and rules, makes them easy to find again.
Scenarios also hide the familiar problem underneath. A car park with a list of cars inside is a set of records with lookup by registration. A queue for a ride at a theme park is a queue. A map of footpaths is a graph. Recognising the familiar problem tells you which structure and algorithm to reach for.
The breakdown also shows what can be tested. Each input has a valid range, so it has normal, boundary and erroneous values. Each constraint has an edge, such as the 20th and the 21st booking. Writing these down early means the tests are ready when the code is, and the examiner sees that the solution has been thought through.
Check yourself. A library lets members borrow up to six books for three weeks. List the stored data the program needs.
Show the answer
It needs each member and the books they have on loan, with each loan's due date. It also needs each book's details and whether it is on the shelf, so it can check availability and the six-book limit.
Section 2
Choosing data structures
Matching the structure to the job
The choice of data structure often decides how easy the rest of the solution is. An array suits a fixed number of items accessed by position, such as the 64 squares of a chessboard. A list suits items that grow and shrink. A queue suits first come, first served, such as a waiting list. A stack suits undo, backtracking and anything that must be reversed.
A dictionary, or hash table, suits lookup by a key, such as a member's record found by membership number. A tree suits data kept in order, or data with a hierarchy, such as folders. A graph suits places and the links between them, such as a road network. Records group the fields of one item, such as a car's registration and entry time.
Common mistake: thinking an array is the right structure for every problem. An array can hold anything, but it makes some jobs slow or awkward. Finding a member by number means searching the whole array, while a hash table goes straight to the record. Undoing in order is natural with a stack and fiddly with an array.
Records, classes and arrays of them
Most scenarios involve many items of the same kind, each with several fields: cars, members, tickets, bookings. Each item is best held as a record, or as an object of a class, with one field for each piece of information. The collection of items is then an array, a list or a hash table of those records.
Writing the record first, with its field names and types, clarifies the whole design. A booking might have a member number, a class identifier and a time. Once the fields are fixed, every algorithm that uses bookings can refer to them by name, which makes the pseudocode much easier to read.
Worked example 3: three choices
A theme park app keeps a waiting list for each ride, lets staff undo their last change, and finds a visitor's ticket by its number. Choose a structure for each job.
| Working | Reason |
|---|---|
| Waiting list: a queue | Visitors ride in the order they joined |
| Undo: a stack of changes | The most recent change is undone first |
| Ticket lookup: a hash table keyed on ticket number | Each lookup takes about one step |
| Each ticket: a record of number, name and ride times | Groups the fields belonging to one ticket |
Worked example 4: the cost of a poor choice
The theme park has 10,000 tickets. Compare finding one ticket by number in an unsorted array with finding it in a hash table.
| Working | Reason |
|---|---|
| Unsorted array, worst case: 10,000 comparisons | Linear search may check every ticket |
| Sorted array with binary search: at most 14 | It halves the tickets at every step |
| Hash table: about 1 step, if collisions are few | The hash of the number gives the position |
| Thousands of lookups a day favour the hash table | The saving is repeated on every lookup |
Structures can be combined. A hash table can map each ride to its own queue. A graph's nodes can be records holding a name and a list of neighbours. In an answer, name the structure, say what each element holds, and give the reason for the choice. "A queue of visitor records, because visitors are served in the order they join" earns more than "a queue".
The choice of structure also affects memory. A two-dimensional array for a seating plan of 20 rows and 30 seats uses 600 cells, whether or not the seats are booked. A hash table uses memory only for the items stored, plus some spare space to keep collisions rare. For most scenarios memory is not the main concern, but a good answer notices when it is.
Check yourself. A word processor must let the user undo many actions in reverse order. Which structure should hold the actions, and why?
Show the answer
A stack, because the most recent action must be undone first. Each new action is pushed on top, and undo pops the top action off, so actions are undone in reverse order.
Section 3
Choosing an algorithm
Counting the cost
Many tasks can be done by more than one algorithm, and the best choice depends on the data. The way to choose is to count the work each one does for the sizes in the scenario. Big O gives the shape of the growth, but at the sizes in a real problem the actual counts often matter more than the order alone.
A common choice is whether to sort data before searching it. Linear search needs no sorting but checks up to n items each time. Binary search needs only about log₂ n comparisons, but the list must be sorted first, which costs about n log₂ n comparisons. Which is cheaper depends on how many searches there will be.
Figure 27.1 plots both approaches against the number of searches. Change the number of searches and the size of the list, then switch on the wrong model.
Sort first, or search as it is?
- Linear each time
- 10,000
- Sort, then binary
- 10,066
- Sorting pays off from
- 11 searches
Common mistake: thinking binary search is always cheaper. Binary search needs a sorted list, and sorting costs far more than one linear search. For only a few searches, linear search on the unsorted list does less work; sorting first pays off only once there are enough searches to share its cost.
Worked example 5: twenty searches
A list of 1,000 unsorted names will be searched 20 times. Compare searching it as it is with sorting it once and using binary search.
| Working | Reason |
|---|---|
| Linear: 20 × 1,000 = 20,000 comparisons | Each search may check every name |
| Sort: about 1,000 × log₂ 1,000, about 9,966 | The cost of an n log n sort, once |
| Binary: 20 × 10 = 200 comparisons | Each search needs at most ten comparisons |
| Total: about 10,166, so sorting first wins | It is about half the linear cost |
Worked example 6: finding the break-even point
For the same list of 1,000 names, find the smallest number of searches for which sorting first is cheaper.
| Working | Reason |
|---|---|
| Linear cost: 1,000 k for k searches | Each search may check every name |
| Sorted cost: 9,966 + 10 k | One sort, then ten per search |
| Sorting wins when 9,966 + 10 k < 1,000 k | Set the costs against each other |
| k > 9,966 ÷ 990, about 10.1, so 11 searches | Round up to a whole number of searches |
Derivation: when sorting first pays off
Let n be the list size and k the number of searches. Linear search costs about k n comparisons. Sorting costs about n log₂ n, and each binary search about log₂ n.
Sorting first is cheaper when the second is smaller than the first. Rearranging for k gives the break-even point.
So for a large list, sorting pays off once there are more searches than about log₂ n, which is only 20 for a million items.
Using Big O sensibly
Big O describes how the work grows, but it hides constant factors and small terms. For small inputs those hidden parts can matter more than the order. That is why the break-even point above is not at one search: sorting has a large fixed cost that binary search's speed must first repay. In a scenario, always check the sizes before deciding.
The same idea explains why real programs often mix algorithms. A library sort may use insertion sort for short runs of items and merge sort for the rest. Each algorithm is used where it does least work, and the choice is made by counting, not by habit.
Other choices
The same counting decides many other choices. For a small list that is nearly sorted, insertion sort is often faster than merge sort, because it does almost no work on items already in place. For finding the shortest route on a map, Dijkstra's algorithm is exact, while A* with a good heuristic explores far fewer places. Each choice should be justified by the scenario's data, not by which algorithm is famous.
Choosing an algorithm also means checking what it needs. Binary search needs sorted data; Dijkstra's algorithm needs edge weights that are not negative; a hash table needs a good hash function and enough spare space. A scenario that breaks one of these needs rules the algorithm out, or calls for an extra step first. Naming the requirement, and showing the scenario meets it, makes the choice convincing.
Sometimes the right choice is to avoid repeated work altogether. If the same totals are needed again and again, keep a running total as each item arrives, rather than adding everything up each time. If the largest value is often needed, keep track of it as items are added. Thinking ahead in this way can turn an O(n) step into an O(1) one.
Check yourself. A program searches a list of 100 items only once. Should it sort the list first? Explain.
Show the answer
No. One linear search takes at most 100 comparisons, while sorting alone takes about 664. Sorting pays off only when there are many searches; for 100 items the break-even point is 8 searches.
Section 4
Writing algorithms from patterns
Common patterns
Most algorithms in the paper are built from a handful of patterns. Learning them well means you rarely start from nothing. Counting uses a variable set to 0 and increased by 1 whenever a condition holds. Totalling adds each value to a running total. Finding a maximum keeps the largest value seen so far, starting from the first item.
Searching loops through the items until it finds a match, then stops. Validating repeats a request until the input meets every rule. Two nested loops compare every item with every other, which is simple but slow. Two pointers, moving in from the ends of a sorted list, can replace nested loops for some problems, such as finding a pair with a given sum.
count = 0
total = 0
largest = scores[0]
for i = 0 to n - 1
if scores[i] >= 50 then count = count + 1 endif
total = total + scores[i]
if scores[i] > largest then largest = scores[i] endif
next i
The loop above combines three patterns in one pass through the data: counting the passes, totalling the scores and finding the largest. Starting largest at the first score, rather than at 0, makes it work even if every score is negative. A single pass is faster and clearer than three separate loops.
Searching and validating
A search pattern loops through the items and stops as soon as it finds a match, using a flag or an early return. Stopping early matters: a search that always checks every item wastes time when the item is near the start. The loop's condition usually combines two tests, such as "not found and not at the end".
A validation pattern asks for input, checks it against every rule, and repeats until the input is valid. Each rule should give its own clear message, so the user knows what to fix. In a scenario, the rules come from the constraints identified at the start, so the breakdown and the validation should match line for line.
Two pointers
The two-pointer pattern starts one pointer at each end of a sorted list. To find two numbers that add up to a target, it adds the numbers at the pointers. If the sum is too small, it moves the left pointer right, to a bigger number. If the sum is too big, it moves the right pointer left. Each step rules out one number for good.
Figure 27.2 compares the two-pointer search with two nested loops. Change the target, then switch on the wrong model.
Two pointers or two loops?
- Pair found
- 14 + 19
- Nested loops
- 23 comparisons
- Two pointers
- 7 comparisons
When an algorithm uses nested loops, count its work by asking how many times the innermost line runs. If the outer loop runs n times and the inner loop runs over the items after the outer one, the inner line runs once for every pair. The derivation below turns that into a formula.
Derivation: the comparisons made by nested loops
On pass i of the outer loop, counting from 1, the inner loop compares item i with every later item, which is n − i comparisons. Adding these over every pass gives
This is the sum of the whole numbers from 1 to n − 1, which has a well-known formula.
So 8 items give 28 comparisons and 1,000 items give 499,500. The leading term is n² ÷ 2, so nested loops are O(n²).
Common mistake: thinking two nested loops make about n comparisons. The inner loop runs once for every pass of the outer loop, so nested loops over n items make up to n(n − 1)/2 comparisons. For 1,000 items that is 499,500, against at most 999 for two pointers.
Worked example 7: comparing the two methods
Find a pair with a sum of 33 in the list 2, 5, 8, 11, 14, 19, 23, 30. Count the comparisons made by nested loops and by two pointers.
| Working | Reason |
|---|---|
| Nested loops try pairs in order: (2, 5), (2, 8) and so on | The outer item is paired with each later one |
| They reach (14, 19) at the 23rd comparison | Every earlier pair has a different sum |
| Two pointers find (14, 19) in 7 comparisons | Each step rules out one number |
| Both give 14 + 19 = 33 | The methods agree on the pair found |
Worked example 8: scaling up
For a sorted list of 1,000 numbers with no pair that adds up to the target, compare the worst-case comparisons of the two methods.
| Working | Reason |
|---|---|
| Nested loops: 1,000 × 999 ÷ 2 = 499,500 | Every pair is tried once, in the worst case |
| Two pointers: 1,000 − 1 = 999 | Each step moves one pointer inwards |
| Nested loops are O(n²); two pointers are O(n) | The counts grow at different rates |
| Two pointers do about 500 times less work | The gap widens as the list grows |
The two-pointer method needs the list sorted. If it is not, sorting it first costs about n log₂ n, which is still far less than n² for large lists. It also does not always win: for a target of 7, the nested loops find 2 + 5 at once, while the pointers take 7 steps. The worst case, not one lucky case, decides which method scales.
Check yourself. Write the pattern, in words, for finding the smallest value in a list.
Show the answer
Set smallest to the first item. Then loop through the remaining items, and whenever an item is less than smallest, set smallest to that item. After the loop, smallest holds the smallest value.
Section 5
Tracing and debugging
Trace tables
A trace table records the value of every variable after each step of an algorithm. It is the most reliable way to work out what code does, and the paper often asks for one. Each column is a variable, or a condition, and each row is one step or one pass through a loop. Outputs get their own column.
Questions on given code come in several forms. Some ask for the output for given inputs. Some ask what the code does in general, which a trace with small values reveals. Others ask you to complete missing lines, where the surrounding code and a quick trace show what each gap must do. All of them reward a careful, written trace rather than a guess.
Filling a trace table carefully means changing only one row at a time, and only the variables the current line changes. A variable that does not change keeps its value, which can be shown by leaving the cell blank or repeating the value, as the question asks. The table makes every step visible, so mistakes are easy to see.
Common mistake: thinking you can trace code reliably in your head without a table. Keeping several changing variables in your head leads to skipped steps and mixed-up values, especially in loops. Writing every change in a table is slower per step but far more accurate, and it shows the examiner your working.
Worked example 9: tracing Euclid's algorithm
Trace the algorithm below for a = 48 and b = 18, and state its output.
while b != 0
r = a MOD b
a = b
b = r
endwhile
print(a)
| Working | Reason |
|---|---|
| Pass 1: r = 48 MOD 18 = 12; a = 18; b = 12 | Eighteen goes into forty-eight twice, leaving twelve |
| Pass 2: r = 18 MOD 12 = 6; a = 12; b = 6 | Twelve goes into eighteen once, leaving six |
| Pass 3: r = 12 MOD 6 = 0; a = 6; b = 0 | Six divides twelve exactly |
| b is now 0, so the loop stops and prints 6 | The loop condition is false at last |
Tracing in the exam
When a question asks for a trace table, use exactly the columns it gives, in the same order. Fill one row each time a variable changes, or each pass, as the question shows. Write outputs in their own column at the moment they happen. If you run out of rows, the table is usually telling you that the algorithm has stopped, or that you have made a mistake.
Tracing is also the best way to understand code you did not write. Pick small values that make the loop run two or three times, trace them, and describe in words what the code does. "It finds the highest common factor of a and b" earns marks that a description of each line does not.
Finding errors
Questions often give code with errors to find and correct. Look first for the common kinds. A loop may run one time too many or too few, especially around n and n − 1 when arrays start at 0. A comparison may be the wrong way round, < instead of >. A variable may start at the wrong value, such as 0 when the data could be negative. A variable may never be updated, so a loop never ends.
Worked example 10: correcting a maximum finder
The function below should return the largest value in an array arr of n items, indexed from 0. Find and correct its three errors.
function largest(arr, n)
max = 0
for i = 1 to n
if arr[i] < max then
max = arr[i]
endif
next i
return max
endfunction
| Working | Reason |
|---|---|
| max = 0 is wrong if every value is negative; use max = arr[0] | Start from a value that is really in the array |
| for i = 1 to n reads arr[n], past the end; use n − 1 | The last index of n items is n minus one |
| arr[i] < max keeps smaller values; use > | Only a larger value should replace the maximum |
| Trace on [−5, −2, −9]: max −5, then −2, then −2 stays | The corrected function returns minus two |
A dry run, tracing code by hand, is how bugs are found on paper. An IDE does the same job on a computer, with breakpoints and watches. In the exam you have only paper, so the trace table is your debugger. Practising trace tables on real code until they are routine is one of the best ways to prepare for the paper.
Tracing with a small, awkward example is the best way to test a correction. A list of negative numbers exposes the wrong starting value; a list of one item exposes loop bounds that are off by one. Choose test data the way a tester would: normal, boundary and unusual.
Check yourself. A loop is written for i = 0 to n to visit every item of an array with n items, indexed from 0. What goes wrong?
Show the answer
The loop runs n + 1 times, so on its last pass it reads arr[n], one place past the end of the array. The bound should be n − 1, so the loop visits indices 0 to n − 1.
Section 6
Evaluating and improving solutions
What makes a good solution
A solution should first be correct: it gives the right output for every valid input, including the edge cases, and rejects invalid input sensibly. Then it should be efficient enough for the data it will meet. It should be readable, with clear names, comments and subroutines, so that someone else can maintain it. And it should use memory sensibly.
These qualities can pull against each other. A faster algorithm may use more memory, as memoisation does, or be harder to read, as some clever tricks are. A solution for a hundred items need not be as fast as one for a hundred million. Evaluating a solution means weighing these qualities for the scenario in front of you.
Common mistake: thinking the fastest solution is always the best one. Speed is one quality among several. A faster method that uses far more memory, or that nobody can understand or maintain, may be worse overall. The best solution is the one that suits the scenario's data, hardware and future changes.
Memoisation and caching
Some solutions repeat the same work many times. The recursive Fibonacci function is the classic case: fib(12) makes 465 calls, because it recomputes the same values again and again. Memoisation stores each value the first time it is worked out. With it, fib(12) needs only 23 calls, at the cost of storing a dozen values.
Caching works the same way outside recursion. A program that looks up the same exchange rate thousands of times a day can fetch it once an hour and keep it. The saving depends on how often the same request repeats, and the cost is the risk that a stored value has gone out of date. Saying both, for the scenario in hand, makes an improvement convincing.
Worked example 11: the effect of memoisation
The plain recursive fib(20) makes 21,891 calls. With memoisation it makes 2n − 1 calls. Compare the two.
| Working | Reason |
|---|---|
| Memoised: 2 × 20 − 1 = 39 calls | Each value is worked out only once |
| Plain: 21,891 calls | Values are recomputed again and again |
| 21,891 ÷ 39 is about 560 times as many | The saving grows rapidly with n |
| Cost: about 20 stored values | Memoisation trades memory for speed |
Readability and maintainability
Code is read far more often than it is written. Meaningful names such as totalCost, rather than t, tell the reader what each variable holds. Subroutines with one clear job each, such as calculateCharge, make the main program read like the plan. Comments should explain why something is done, not repeat what the line says.
A maintainable solution is easy to change when the scenario changes. If the car park's hourly rate is stored as a constant at the top of the program, a price rise needs one edit. If £2 is typed into ten places, someone will miss one. Examiners reward solutions that are built to change.
Performance modelling
To judge whether a solution is fast enough, predict its time for the real data. If an O(n²) method takes 0.5 seconds for 1,000 items, it will take 100² = 10,000 times as long for 100,000 items. An O(n) method that also takes 0.5 seconds for 1,000 items would take only 100 times as long.
Worked example 12: will it scale?
A school's O(n²) duplicate checker takes 0.5 s for 1,000 records. The exam board will run it on 100,000 records. Predict its time, and that of an O(n) checker using a hash table, also 0.5 s for 1,000.
| Working | Reason |
|---|---|
| The data grows by a factor of 100 | From 1,000 records to 100,000 records |
| O(n²): 0.5 × 100² = 5,000 s, about 83 minutes | The time grows with the square of n |
| O(n): 0.5 × 100 = 50 s | The time grows in proportion to n |
| The hash table checker is the one to use | It uses more memory but scales far better |
Robustness
A robust solution copes sensibly with input it was not expecting. A program that crashes on an empty file, or accepts a negative number of tickets, is fragile. Validation at the point where data enters, sensible defaults and clear error messages make it robust. In an evaluation, saying which unexpected inputs the solution handles, and which it does not, shows real understanding.
Writing an evaluation
An evaluation in an answer should be specific. Say what the solution does well, with a reason. Then give a real limitation and a concrete improvement. "It uses nested loops, which are O(n²), so for 100,000 records a hash table would be much faster" is a strong point. "It could be more efficient" earns nothing.
Look also for what the solution does not handle. Does it cope with an empty list, a tie, or input of the wrong type? Would it still work if the scenario grew, for example to two car parks instead of one? Naming a missing case, and saying how to handle it, shows the examiner you have tested the solution in your head as well as on paper.
Check yourself. A solution sorts a list of 50 names with bubble sort. Is it worth replacing with merge sort? Explain.
Show the answer
Probably not. For 50 names, bubble sort's 1,225 or so comparisons take a tiny fraction of a second, and bubble sort is simpler. Merge sort is worth it for large lists, where n² grows far faster than n log n.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Scenario breakdown | Inputs, outputs, stored data, constraints | A car park's entry and exit times | Do it before writing code |
| Assumption | A sensible rule where the scenario is silent | Each day capped separately | State it at the start |
| Choosing a structure | Matching the structure to the job | Queue, stack, hash table, graph | Give the reason |
| Sort, then binary search | Pay once to sort, then search fast | 20 searches of 1,000 names | Wins after about log₂ n searches |
| Counting, totalling, maximum | Patterns in one pass through data | count = count + 1 | Start maximum at the first item |
| Two pointers | Move inwards from both ends of a sorted list | Pair with a given sum | O(n), against O(n²) for nested loops |
| Nested loops | Compare every item with every other | All pairs | n(n − 1) ÷ 2 comparisons |
| Trace table | Every variable after every step | Euclid's algorithm | One change per row |
| Common errors | Off by one, wrong comparison, wrong start | for i = 1 to n | Test with awkward data |
| Memoisation | Store results to avoid repeated work | Fibonacci | Trades memory for speed |
Programming task
Programming task: a pair finder
Aim
Write a Python program that finds two numbers in a sorted list whose sum equals a target, using two pointers. It must report the pair found, or that there is none, and the number of comparisons made.
Design
The function keeps two indices, lo starting at the first item and hi at the last. While lo is less than hi, it adds the two numbers. If the sum equals the target, it returns the pair. If the sum is too small, it moves lo one place right; if too big, it moves hi one place left. If the pointers meet, there is no pair.
A counter records each comparison, so the program can show how few steps the method needs. A second function using nested loops can be run on the same data, to compare the counts.
Code
def pair_sum(values, target):
lo = 0
hi = len(values) - 1
steps = 0
while lo < hi:
steps = steps + 1
total = values[lo] + values[hi]
if total == target:
return (values[lo], values[hi]), steps
if total < target:
lo = lo + 1
else:
hi = hi - 1
return None, steps
values = [2, 5, 8, 11, 14, 19, 23, 30]
for target in [33, 32, 7, 100, 53]:
pair, steps = pair_sum(values, target)
print(target, pair, steps, "comparisons")
print(pair_sum([], 10), pair_sum([5], 10))
The loop condition lo < hi stops the pointers before they cross, so no number is paired with itself. Returning None with the step count, rather than printing inside the function, lets the caller decide what to do with the result.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | target 33 | (14, 19) in 7 comparisons | Matches worked example 7 |
| 2 | target 32 | (2, 30) in 1 comparison | The pair is at the two ends |
| 3 | target 7 | (2, 5) in 7 comparisons | The pair is at the start |
| 4 | target 100 | None in 7 comparisons | No pair is possible |
| 5 | target 53 | (23, 30) in 7 comparisons | The pair is at the end |
| 6 | empty list, target 10 | None in 0 comparisons | The loop must not run |
| 7 | list [5], target 10 | None in 0 comparisons | One item cannot be paired with itself |
Evaluation
The program gives the expected pair and count in every test. That includes the edge cases of an empty list and a single item, where it correctly returns None without an error. Even when there is no pair, it makes at most n − 1 comparisons, against 28 for nested loops on these 8 items.
The program assumes the list is sorted, which is its precondition; an unsorted list would give wrong answers. An improvement would check this, or sort the list first. Another would return every pair with the target sum, not just the first, which needs both pointers to move inwards after a match.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Name the four things to identify in a scenario before writing code.
Worked solution to Q1
Identify the inputs the program is given, the outputs it must produce, the data it must store, and the constraints, the rules and limits it must obey.
Q2. State which data structure suits a printer's list of waiting jobs, and give a reason.
Worked solution to Q2
A queue suits the printer's jobs, because they should be printed in the order they were sent. A queue is first in, first out, so the oldest job is printed next.
Q3. Describe what a trace table records.
Worked solution to Q3
A trace table records the value of each variable, and any output, after each step or pass of an algorithm. Each column is a variable and each row is one step.
Rung 2: Application
Q4. Find the charge for a stay of 9 hours 5 minutes, at £2 per hour or part hour, capped at £15 a day.
Worked solution to Q4
The stay counts as 10 hours, because any part of an hour is charged in full. Ten hours at £2 is £20, which is above the daily cap, so the charge is £15.
Q5. Using Euclid's algorithm, find the highest common factor of a = 30 and b = 12, showing each pass.
Worked solution to Q5
Pass 1: 30 MOD 12 = 6, so a becomes 12 and b becomes 6. Pass 2: 12 MOD 6 = 0, so a becomes 6 and b becomes 0. The loop stops and prints 6.
Q6. Nested loops search 20 items for a pair. What is the largest number of comparisons they can make?
Worked solution to Q6
Every pair is tried once, so the worst case is n(n − 1) ÷ 2 = 20 × 19 ÷ 2 = 190 comparisons. Two pointers on the sorted list would need at most 19.
Q7. Five searches will be made of a list of 1,000 unsorted names. Compare linear search with sorting first and using binary search.
Worked solution to Q7
Linear search costs 5 × 1,000 = 5,000 comparisons. Sorting costs about 9,966, plus 5 × 10 for the searches, about 10,016. So for only five searches, linear search does less work.
Rung 3: Analysis
Q8. Explain why a hash table is better than an unsorted array for finding a member's record by number in a club with 5,000 members.
Worked solution to Q8
An unsorted array needs a linear search, up to 5,000 comparisons per lookup. A hash table works out the record's position from the number, so a lookup takes about one step if collisions are few.
Q9. A function finds the average of n marks with total = 0, then for i = 1 to n, total = total + marks[i], with marks indexed from 0. Identify the error and correct it.
Worked solution to Q9
The loop starts at index 1, skipping marks[0], and reads marks[n], past the end. It should run for i = 0 to n − 1, so it visits every mark exactly once.
Q10. For a list of 100 items, find the smallest number of searches for which sorting first is cheaper.
Worked solution to Q10
Sorting costs about 100 × log₂ 100, about 664, then 7 comparisons per binary search. Linear costs 100 per search. With 8 searches, sorted costs about 720 and linear 800, so the break-even point is 8 searches.
Q11. Predict the time for 10,000 records of an O(n²) program that takes 0.5 s for 1,000 records.
Worked solution to Q11
The data grows by a factor of 10, so an O(n²) time grows by 10² = 100. The predicted time is 0.5 × 100 = 50 seconds for 10,000 records.
Rung 4: Stretch
Q12. Explain, with the derivation, why sorting first pays off after only about 20 searches of a million items.
Worked solution to Q12
Sorting pays off once the number of searches exceeds about log₂ n. For a million items, log₂ 1,000,000 is about 20, so after about 20 searches the sort has paid for itself.
Q13. For a target of 7 in the list 2, 5, 8, 11, 14, 19, 23, 30, nested loops find the pair in 1 comparison and two pointers in 7. Explain why two pointers are still the better choice.
Worked solution to Q13
One lucky target favours the nested loops, but their worst case is n(n − 1) ÷ 2 comparisons, against n − 1 for two pointers. For large lists the worst case decides which method scales, so two pointers win.
Q14. The memoised Fibonacci function makes 2n − 1 calls. How many does it make for fib(30), and roughly how much memory does it need?
Worked solution to Q14
It makes 2 × 30 − 1 = 59 calls, against 2,692,537 for the plain version. It stores one value for each of fib(0) to fib(30), about 31 values, which is very little memory.
Exam practice
Exam technique and worked answer workshop
Before writing any code for a scenario question, write a short plan: the inputs, outputs, stored data and the structures you will use. Examiners credit a clear plan, and it keeps your code on track.
Write pseudocode that an examiner can follow: meaningful names, consistent indentation and one statement per line. Any reasonable pseudocode earns full marks; exact syntax does not matter, but the logic must be unambiguous. Comment any line whose purpose is not obvious.
When asked to evaluate or compare, give a specific reason tied to the scenario's data, such as a size or a frequency. When asked to trace, use a table and change one row at a time.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
A gym's booking system lets members book exercise classes. Each class has a time, a room and up to 20 places. Members book by membership number and may cancel up to an hour before.
(a) Identify two inputs and one output of the booking system. [3]
(b) Identify one constraint the system must check. [1]
Mark scheme for exam question 1
- B1 an input, such as the membership number
- B1 another input, such as the class chosen or a cancellation request
- B1 an output, such as a booking confirmation or a message that the class is full
- B1 a constraint, such as at most 20 places, or cancelling no later than an hour before
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
The gym's system must keep a waiting list for each full class, find a member's record quickly from their membership number, and let staff undo their last change.
(a) Name a suitable data structure for each of these three jobs. [3]
(b) Justify your choice for any two of them. [2]
Mark scheme for exam question 2
- B1 waiting list: a queue
- B1 member lookup: a hash table or dictionary keyed on membership number
- B1 undo: a stack
- B1 a justification, such as the queue serves members in the order they joined
- B1 a second justification, such as the stack undoes the most recent change first, or the hash table finds a record in about one step
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
A program must search an unsorted list of 1,000 names 20 times. Sorting the list takes about 9,966 comparisons, and each binary search then takes at most 10.
(a) Calculate the total comparisons for linear search and for sorting then binary search. [3]
(b) Calculate the smallest number of searches for which sorting first is cheaper. [2]
Mark scheme for exam question 3
- M1 linear: 20 × 1,000
- A1 20,000 comparisons
- B1 sorting then searching: 9,966 + 200 = 10,166
- M1 9,966 + 10k < 1,000k
- A1 11 searches
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
Complete a trace table for the algorithm below with a = 48 and b = 18, and state its output.
while b != 0
r = a MOD b
a = b
b = r
endwhile
print(a)
Mark scheme for exam question 4
- B1 pass 1: r = 12, a = 18, b = 12
- B1 pass 2: r = 6, a = 12, b = 6
- B1 pass 3: r = 0, a = 6, b = 0
- B1 the loop stops when b is 0
- B1 output 6
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A bank must check a day's 50,000 transactions for pairs whose amounts add up to exactly £10,000, a sign of possible fraud. One programmer proposes two nested loops over the transactions. Another proposes sorting the amounts and using two pointers. Evaluate the two proposals.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced evaluation of both proposals, linked to the bank's data. It compares their efficiency with figures or orders of growth, and considers correctness, memory and simplicity. The answer reaches a justified recommendation. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): compares the proposals with some reasons, but the evaluation is one-sided or not linked to the bank's data.
Level 1 (1–2 marks): some relevant points, such as that one is faster, with little development. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- nested loops try every pair: about 50,000 × 49,999 ÷ 2, over a billion comparisons
- nested loops are O(n²) but simple to write and need no extra memory or sorting
- two pointers need the amounts sorted first, about n log₂ n, roughly 800,000 comparisons
- the pointer pass then takes at most n − 1 comparisons, so the whole method is O(n log n)
- sorting loses the original order, so each amount must keep a link to its transaction
- the two-pointer method as written finds one pair; finding every pair needs more care
- both must be tested, for example with no pairs, one pair and repeated amounts
- conclusion: the sorted two-pointer method is far faster for 50,000 transactions and should be used, with care to report every pair
Annotated model answer: exam question 5
"Nested loops would compare every transaction with every other one. For 50,000 transactions that is about 50,000 × 49,999 ÷ 2, over a billion comparisons, because the method is O(n²). It is simple to write and needs no extra memory." (Efficiency with a figure, plus a strength.)
"Sorting first costs about n log₂ n, roughly 800,000 comparisons. The two pointers then need at most 49,999 more. So the whole method is O(n log n), over a thousand times less work here." (The second proposal costed and compared.)
"But sorting loses the original order, so each amount must carry a link to its transaction. The two-pointer method as described stops at the first pair. The bank needs every suspicious pair, so it must be extended to keep searching." (Weaknesses of the faster method.)
"The bank should use the sorted two-pointer method, because nested loops would be far too slow for 50,000 transactions a day. It must be extended to report every pair and tested with repeated amounts." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It costs both methods with figures, weighs their strengths and weaknesses and recommends one for the bank's data.
Exam question 6 (4 marks · Paper 01 · about 5 minutes)
A sorted list holds 1,000 numbers, and no two of them add up to the target.
(a) Calculate the comparisons made by two nested loops and by two pointers. [2]
(b) State the order of growth of each method. [2]
Mark scheme for exam question 6
- B1 nested loops: 1,000 × 999 ÷ 2 = 499,500
- B1 two pointers: 999
- B1 nested loops are O(n²)
- B1 two pointers are O(n)
Exam question 7 (5 marks · Paper 02 · about 7 minutes)
The function below should return the largest value in an array arr of n items, indexed from 0. It contains three errors.
function largest(arr, n)
max = 0
for i = 1 to n
if arr[i] < max then
max = arr[i]
endif
next i
return max
endfunction
Identify and correct each error.
Mark scheme for exam question 7
- B1 max = 0 gives a wrong answer when every value is negative
- B1 correct it to max = arr[0]
- B1 for i = 1 to n reads arr[n], past the end of the array
- B1 correct it to for i = 1 to n − 1
- B1 arr[i] < max should be arr[i] > max, so larger values replace the maximum
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function hasPair(values, n, target) that returns true if two different items of the sorted array values, of length n, add up to target, and false otherwise. Use two pointers.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a left pointer starting at 0 and a right pointer at n − 1
- B1 a loop that continues while the left pointer is less than the right
- B1 returning true when the two items add up to the target
- M1 moving the left pointer right when the sum is too small, and the right pointer left when it is too big
- A1 returning false after the loop, when the pointers meet
Annotated model answer: exam question 8
function hasPair(values, n, target)
lo = 0
hi = n - 1
while lo < hi
total = values[lo] + values[hi]
if total == target then
return true
elseif total < target then
lo = lo + 1
else
hi = hi - 1
endif
endwhile
return false
endfunction
The header earns the first mark, and the two starting pointers earn the second. The loop condition lo < hi earns the third, so no item is paired with itself. Returning true on a match earns the fourth. Moving the correct pointer for each case earns the method mark, and returning false once the pointers meet earns the last.
Connections
Synoptic link
This chapter draws on the whole of the algorithms and programming course. Reading a scenario uses the habits of Computational thinking. Choosing structures uses Arrays, records, stacks and queues and Linked lists, hash tables, graphs and trees. Choosing algorithms uses Searching and sorting algorithms and Algorithm analysis and Big O notation.
Writing and tracing use Programming constructs and Subroutines and recursion, and memoisation comes from the recursion taught there. Testing a solution with normal, boundary and unusual data uses Development environments, testing and computational methods.
Synoptic question 1. Merge sort is used to sort 1,024 items before a two-pointer search. How many levels of halving does it have?
Answer to synoptic question 1
Each level halves the parts, and 2¹⁰ = 1,024, so merge sort has 10 levels of halving. It then merges back up through the same 10 levels, doing about 1,024 comparisons at each.
Recap
Recap and next step
- Before writing code, break a scenario into inputs, outputs, stored data and constraints, and state any assumption.
- Choose each data structure to fit its job, such as a queue for waiting, a stack for undo and a hash table for lookup, and give the reason.
- Choose algorithms by counting their work for the scenario's sizes; sorting before searching pays off after about log₂ n searches.
- Build algorithms from patterns: counting, totalling, maximum, searching, validating and two pointers, which replace O(n²) nested loops with O(n).
- Trace code with a table, one change per row, and look for off-by-one bounds, reversed comparisons and wrong starting values.
- Evaluate solutions for correctness, efficiency, memory and readability; memoisation and better structures improve speed at some cost.
Next chapter: this is the last chapter of the course. Return to any earlier chapter to practise its exam questions, using the method from this one.
For your exam board
OCR A Level Computer Science (H446): this chapter draws together sections 2.1, Elements of computational thinking, 2.2, Problem solving and programming, and 2.3, Algorithms, in Component 02, and prepares for the scenario-based questions of its Section B.
AQA A Level Computer Science (7517): the fundamentals of programming, fundamentals of data structures, fundamentals of algorithms and the systematic approach to problem solving sections cover this material, assessed on Paper 1 and in the non-exam assessment.