A Level Computer Science · Chapter 16 · Component 01: Computer systems
Arrays are fast to read but rigid, so programs that grow, search and connect data use structures built from pointers: linked lists, hash tables, graphs and trees.
This chapter teaches four structures that go beyond a simple row of cells. You will trace pointers through a linked list, place keys in a hash table and deal with collisions, represent graphs, and build and traverse binary search trees.
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:
- describe a linked list with nodes, pointers, a head pointer and a free list
- trace insertion and deletion in a linked list stored in an array
- calculate hash values and load factors, and explain what makes a good hash function
- resolve collisions by linear probing and by chaining, and search a hash table
- represent a graph as an adjacency matrix or an adjacency list, and choose between them
- build a binary search tree, search it, and give its pre-order, in-order and post-order traversals
- choose a suitable structure for a problem and justify the choice
Time: three sessions, about 4 hours, plus the programming task.
You need first: arrays, records, stacks and queues from Arrays, records, stacks and queues, and Big O notation from Algorithm analysis and Big O notation.
The big picture
The big picture
Imagine a class list kept in alphabetical order in an array. A new pupil, Ben, joins. To put him in place, every name after his must shift one cell to make room. With thirty names that is a moment's work. With thirty million, it is a serious delay every time someone joins.
A linked list avoids the shuffle. Each item carries a pointer to the next one, so the order lives in the pointers rather than in the positions. Ben can be stored in any free cell, and two pointers change to slot him into place.
Now imagine finding one pupil among thirty million. A sorted array allows a binary search, about 25 steps. A hash table does better still. It turns the name itself into a cell number, so the computer can usually go straight to the right place in one step.
Some data is not a list at all. Roads join towns, web pages link to other pages, and friends link to friends. A graph stores these connections directly, as nodes joined by edges.
A tree is a special kind of graph, with a single root and branches that never loop back. A binary search tree keeps its keys so that smaller ones go left and larger ones go right. Searching it is like a binary search that grows as data arrives.
Each of these structures is built from the same parts: records for the items, and pointers to join them. In an exam, they are usually stored in arrays, with each pointer holding the index of another cell. Tracing them by hand is mostly a matter of following those pointers carefully.
The key question for each structure is the same as in the previous chapter. Which operations does it make cheap, and which does it make expensive? Answering that tells you when to use it.
Section 1
Linked lists
Nodes and pointers
A linked list is a dynamic data structure made of nodes. Each node holds some data and a pointer to the next node. A separate head pointer holds the address of the first node. The last node's pointer is null, which marks the end of the list.
The nodes do not need to sit next to each other in memory. The order of the list comes entirely from the pointers. To visit the items in order, start at the head and follow each pointer in turn until you reach null. This is called traversing the list.
Common mistake: following the array order instead of the pointers. When a linked list is stored in an array, the nodes can be in any cells. Reading the cells from index 0 upwards gives the storage order, not the list order. Always start at the head and follow the pointers.
Storing a linked list in an array
In exams, a linked list is usually stored in two parallel arrays, or an array of records. One holds the data and the other holds the next pointers, as indices. A pointer of null, often written −1 or ∅, means there is no next node.
Worked example 1: traversing a linked list
Use the table above to list the names in order. Head is 1.
| Working | Reason |
|---|---|
| Start at node 1: Ali, next 3 | The head pointer gives the first node |
| Node 3: Dev, next 0 | Follow the pointer from Ali |
| Node 0: Kim, next 2; node 2: Sam, next null | Keep following pointers until null |
| Order: Ali, Dev, Kim, Sam | The null pointer ends the traversal |
Linked lists against arrays
A linked list can grow and shrink one node at a time, and inserting or deleting needs only a few pointer changes. No other item moves. That makes insertion and deletion cheap once you have found the right place.
The cost is access. There is no way to jump to the fifth item, because its address is not known until the fourth item is reached. Finding an item means traversing from the head, which is O(n). Each node also uses extra memory for its pointer.
Searching a linked list is always linear, even when it is sorted. A binary search needs to jump to the middle item, and a linked list cannot do that cheaply. Reaching the middle means walking half the list first, which throws away the advantage.
So a linked list is the right choice when items are added and removed often, and mostly visited in order. It is the wrong choice when items must be reached by position or found quickly. Queues and stacks are often built from linked lists, because they only ever touch the ends.
Worked example 2: inserting at the front
A list holds 1,000 items. Compare the moves needed to add a new item at the front of an array and at the front of a linked list.
| Working | Reason |
|---|---|
| Array: all 1,000 items shift one cell along | The first cell must be emptied first |
| That is 1,000 moves, which is O(n) | The cost grows with the number of items |
| Linked list: the new node points to the old first node | Its next pointer takes the old head value |
| The head points to the new node: 2 pointer changes, O(1) | No existing node moves at all |
Static and dynamic structures
An array is a static structure: its size is fixed when it is created, and the memory is set aside in one block. A linked list is a dynamic structure: it takes memory one node at a time, as items arrive, and gives it back as they leave. That makes it a good fit when you cannot predict how many items there will be.
A static structure never runs out of space unexpectedly in the middle of a task, and its memory use is easy to predict. A dynamic structure wastes no space on empty cells, but every node pays for its pointer. Neither is better in general; it depends on the job.
Check yourself. A linked list has head 2. Node 2 holds P with next 0, node 0 holds Q with next 1, and node 1 holds R with next null. Give the list in order.
Show the answer
Start at the head, node 2, which holds P. Its pointer leads to node 0, Q, and then to node 1, R, whose pointer is null. The order is P, Q, R.
Section 2
Inserting into and deleting from a linked list
The free list
When a linked list lives in an array, the unused cells are kept in a second linked list, called the free list. A free pointer holds the index of the first free node. To add an item, take a node from the front of the free list. To delete an item, return its node to the free list.
At the start, every node is free and they are linked in order: 0 points to 1, 1 to 2, and so on. The free pointer is 0 and the head is null. As items are added, nodes move from the free list into the main list.
If the free pointer is null, every node is in use and the list is full. An insertion must check this first, just as a stack checks for overflow. In a language with dynamic memory, new nodes can be created as needed instead, and there is no fixed free list to run out.
Inserting in order
To insert an item into an ordered list, first take a free node and store the item in it. Then traverse the list to find the node that should come before it. Point the new node at that node's successor, then point that node at the new node.
Common mistake: changing the pointers in the wrong order. If the previous node is pointed at the new node first, the address of the rest of the list is overwritten and lost. Always set the new node's pointer before changing the previous node's pointer.
If the new item comes before the first item, it becomes the new head. Its pointer takes the old head, and the head pointer takes the new node. If the list is empty, the new node becomes the head and its pointer is null.
Finding the place to insert is the slow part, because the list must be traversed. The pointer changes themselves take a fixed number of steps, however long the list is. That is why inserting is described as O(1) once the position is known, but O(n) overall for an ordered list.
procedure insert(item)
if free == null then
print("list full")
return
endif
new = free
free = next[free]
data[new] = item
if head == null OR item < data[head] then
next[new] = head
head = new
else
p = head
while next[p] != null AND data[next[p]] < item
p = next[p]
endwhile
next[new] = next[p]
next[p] = new
endif
endprocedure
The loop stops at the last node whose item comes before the new one. The two lines after it are the pointer changes, in the safe order: the new node first, then the previous node.
Worked example 3: inserting a node
Insert Ben into the list from section 1, where head is 1 and free is 4.
| Working | Reason |
|---|---|
| Take node 4 from the free list and store Ben; free becomes 5 | Node 4's pointer gave the next free node |
| Traverse: Ali comes before Ben, Dev after | The list is kept in alphabetical order |
| Set node 4's pointer to 3, Dev's node | Ben must point to Ali's old successor |
| Set Ali's pointer, node 1, to 4 | Ali now points to Ben, which completes the insertion |
The new order is Ali, Ben, Dev, Kim, Sam. Ben is stored in node 4, at the end of the array, but the pointers put him second.
Deleting a node
To delete an item, traverse the list, keeping track of the previous node. When the item is found, point the previous node at the item's successor. Then return the deleted node to the free list, by pointing it at the old free node and making it the new free pointer.
Common mistake: deleting a node without updating the previous pointer. Blanking the data in a node leaves the previous node still pointing at it. A traversal then meets an empty node in the middle of the list. The previous node must be re-pointed past the deleted one.
Figure 16.1 stores a list of names in an array. Insert names with the slider, then delete one, and watch which pointers change. Then switch on the wrong model, which only blanks the data.
A linked list stored in an array
- Traversal
- Ali → Kim → Sam
- Head pointer
- 1
- Free list starts at
- 3
Worked example 4: deleting a node
Delete Dev from the list Ali, Dev, Kim, Sam, where head is 1, Dev is node 3 and free is 4.
| Working | Reason |
|---|---|
| Traverse from the head: Ali, then Dev at node 3 | Keep track of the previous node, Ali |
| Set Ali's pointer to Dev's pointer, 0 | Ali now skips Dev and points to Kim |
| Set node 3's pointer to the old free value, 4 | The deleted node joins the free list |
| Set free to 3: the list is Ali, Kim, Sam | Node 3 is now the first free node |
Other kinds of linked list
A doubly linked list gives each node a second pointer, to the previous node. It can be traversed in both directions, and deleting a node no longer needs a separate previous pointer. The cost is one more pointer per node to store and update.
A circular linked list points its last node back to the first instead of to null. It suits data that cycles, such as players taking turns in a game.
Deleting the first node is a special case. There is no previous node to re-point, so the head pointer itself takes the deleted node's pointer. Forgetting this case is a common bug in real programs, so test it on purpose.
Tracing tips
When you trace a linked list by hand, keep three things in view: the head pointer, the free pointer, and the next column. After every change, traverse the whole list again from the head to make sure it still reaches null. A loop that never reaches null means a pointer was set wrongly.
Check yourself. In a linked list stored in an array, why does a deleted node go back on the free list?
Show the answer
So that the cell can be reused. The free list holds every unused node, and the next insertion takes a node from it. Without returning the node, that cell would be lost until the program ends.
Section 3
Hash tables
Going straight to the data
A hash table stores items in an array, but chooses each item's position from the item's own key. A hash function turns the key into a slot number. To find the item later, the program hashes the key again and looks in that slot.
A simple hash function for numbers is key MOD n, for a table of n slots. The remainder is always between 0 and n − 1, so it is always a valid slot. For a table of 10 slots, key 27 goes in slot 7, and key 18 goes in slot 8.
Hashing strings
Strings must first be turned into a number. A simple way adds the character codes of every letter, then takes MOD n. Real hash functions mix the letters more thoroughly, so that similar keys spread out.
One common improvement multiplies the running total by a small prime before adding each letter. Then CAT and ACT give different totals, because the position of each letter now matters. Another uses a prime number of slots, which helps keys spread out evenly when they share patterns.
Worked example 5: hashing a string
Use the hash function "sum of character codes MOD 11" to hash CAT and ACT. The codes are A = 65, C = 67 and T = 84.
| Working | Reason |
|---|---|
| CAT: 67 + 65 + 84 = 216 | Add the code of every character |
| 216 MOD 11 = 7, since 11 × 19 = 209 | The remainder gives the slot |
| ACT has the same letters, so the same total, 216 | Adding ignores the order of the letters |
| ACT also hashes to 7: a collision | Two different keys share one slot |
What makes a good hash function
A good hash function is quick to calculate, always gives a valid slot, and spreads keys evenly across the table. It must always give the same slot for the same key, or the item could never be found again.
Common mistake: thinking a hash function gives a unique slot for every key. There are far more possible keys than slots, so different keys must sometimes share a slot. That is a collision. A hash table must plan for collisions rather than hope they never happen.
The load factor
The load factor is the fraction of slots in use: the number of items divided by the number of slots. A low load factor means few collisions and fast access. As it rises towards 1, collisions become common and the table slows down.
Worked example 6: the load factor
A hash table has 10 slots and holds 7 keys. Find the load factor, and say what the program should do if it rises much further.
| Working | Reason |
|---|---|
| Load factor = 7 ÷ 10 = 0.7 | Items divided by slots |
| 70% of the slots are in use | A high load factor means more collisions |
| When it passes a limit, often about 0.7, build a bigger table | A larger table spreads the keys again |
| Rehash every key into the new table | Each key's slot depends on the table size |
Rehashing takes O(n) time, but it happens rarely. Most of the time an insertion or search is O(1), which is why hash tables are used for dictionaries, caches and databases.
Python's dictionary is a hash table. When you write ages["Asha"], Python hashes the string "Asha" to find the slot, so looking up a value takes about the same time however many entries the dictionary holds. The same idea lets a database find a record from its key without reading the whole file.
Hash tables do have weaknesses. They keep no useful order, so listing the keys alphabetically needs a separate sort. A bad hash function, or keys that happen to share a pattern, can pile many keys into a few slots. In the worst case every key collides, and a search becomes O(n).
Choosing the table size
The size of the table matters as much as the hash function. If keys are all multiples of 10 and the table has 10 slots, every key lands in slot 0. A prime size, such as 11 or 13, breaks up patterns like this, because few keys share a factor with it.
Check yourself. Using key MOD 12, which slot does key 50 go in, and why must slot numbers stay below 12?
Show the answer
50 MOD 12 = 2, because 12 × 4 = 48, leaving 2. A table of 12 slots has indices 0 to 11, and a remainder after dividing by 12 can never be 12 or more.
Section 4
Collisions
Linear probing
Linear probing deals with a collision by trying the next slot, then the next, until it finds an empty one. The search wraps round from the last slot to slot 0. Each slot examined is called a probe.
To search, hash the key and start at that slot. If the slot holds the key, it is found. If not, move to the next slot and try again. If an empty slot is reached first, the key is not in the table, because it would have been placed there.
Common mistake: overwriting a key after a collision. When a new key hashes to a slot that is already full, it must not replace the key there. The old key would be lost and could never be found. The new key goes in the next free slot, or joins a chain.
Worked example 7: linear probing
Insert 27, 18, 29, 28, 39, 13 and 16 into a table of 10 slots, using key MOD 10 and linear probing.
| Working | Reason |
|---|---|
| 27, 18 and 29 go straight into slots 7, 8 and 9 | No other key is there yet |
| 28 hashes to 8, which is full; 9 is full; it goes in slot 0 | Probing wraps round after slot 9 |
| 39 hashes to 9, full; 0 is full; it goes in slot 1 | Three probes to find a free slot |
| 13 and 16 go straight into slots 3 and 6 | Their home slots are empty |
Worked example 8: searching with linear probing
Search the table above for 39, then for 19.
| Working | Reason |
|---|---|
| 39 hashes to 9, which holds 29; slot 0 holds 28 | Not a match, so keep probing |
| Slot 1 holds 39: found after 3 probes | The search follows the same path as the insertion |
| 19 hashes to 9: slots 9, 0 and 1 hold other keys | Keep probing past each mismatch |
| Slot 2 is empty, so 19 is not in the table | It would have been placed in the first empty slot |
Common mistake: stopping a search at the home slot. With linear probing, a key may sit several slots past the one its hash gives. Checking only the home slot reports keys as missing when they are in the table. Keep probing until the key or an empty slot is found.
Clustering
Linear probing tends to build clusters, runs of full slots next to each other. A key that hashes anywhere into a cluster lands at its end, which makes the cluster longer still. Long clusters mean long searches, so performance falls quickly as the load factor rises.
Deleting from a probed table needs care too. If a key is simply removed, the empty slot breaks the path to keys stored beyond it. Tables mark deleted slots with a special value instead, so searches continue past them.
Linear probing has one big advantage: everything lives in a single array. There are no extra lists to create, and neighbouring slots are close together in memory. When the load factor is kept low, it is often the fastest method in practice.
Chaining
Chaining stores a list of keys in each slot instead of a single key. Every key that hashes to a slot is added to that slot's list. To search, hash the key and look through the list in that slot only.
Figure 16.2 places the same keys by linear probing and by chaining. Add keys with the slider and compare where the collisions go. Then switch on the wrong model, which overwrites the earlier key.
Hashing with collisions
- Collisions
- 1
- Load factor
- 0.4
- Most probes for one key
- 3
Worked example 9: chaining
Insert the same seven keys into a table of 10 slots using chaining.
| Working | Reason |
|---|---|
| 27, 13 and 16 go into the lists at slots 7, 3 and 6 | Each starts a list on its own |
| 18 goes in slot 8, then 28 joins it: slot 8 holds 18, 28 | Both keys hash to 8 |
| 29 goes in slot 9, then 39 joins it: slot 9 holds 29, 39 | Both keys hash to 9 |
| Two collisions; the longest list holds 2 keys | No key ever leaves its home slot |
Chaining never fills up, and clusters cannot form, because each key stays in its home slot. The cost is the memory for the lists, and a slower search if many keys share one slot.
With chaining, the average length of a list equals the load factor. A load factor of 2 means two keys per slot on average, so a search checks about two keys. The table still works above a load factor of 1, which probing cannot do, but it slows down steadily as the lists grow.
Comparing the two methods
Linear probing keeps every key in the table itself, so the load factor can never pass 1. It is simple and quick while the table is fairly empty, but clusters make it slow as it fills. Chaining copes with any number of keys and never clusters, but it needs extra memory for its lists.
Both methods give the same answer to a search; they differ only in speed and memory. In an exam, read carefully which method is described, and follow it exactly.
Check yourself. Using chaining with key MOD 5, where do the keys 12, 22 and 7 go, and how many keys share a slot?
Show the answer
12 MOD 5 = 2, 22 MOD 5 = 2 and 7 MOD 5 = 2, so all three go in the list at slot 2. Three keys share one slot, which shows how a poor choice of keys or table size can defeat a hash table.
Section 5
Graphs as data structures
Nodes and edges
A graph is a set of nodes, also called vertices, joined by edges. In an undirected graph, each edge works both ways, like a two-way road. In a directed graph, each edge has a direction, like a one-way street or a link from one web page to another. A weighted graph gives each edge a value, such as a distance or a cost.
Common mistake: thinking every graph edge works in both directions. In a directed graph, an edge from A to B does not let you travel from B to A. Adding the reverse edge in an adjacency list or matrix records a connection that does not exist.
Two representations
An adjacency matrix is a 2D array with a row and a column for every node. The entry in row A, column B records whether there is an edge from A to B, or its weight. An adjacency list stores, for each node, a list of its neighbours.
A matrix answers "is there an edge from A to B?" in one step, by looking up a single cell. But it needs n² cells, even if most are empty. A list uses space only for the edges that exist, but checking for one edge means searching a node's list.
Derivation: the space used by each representation
For a graph of n nodes, the matrix has one row and one column for every node, whatever the number of edges.
An adjacency list stores each undirected edge twice, once in the list of each end. For e edges, that is 2e entries, plus one list for each node.
For a sparse graph, e is close to n, so the list is O(n) while the matrix is O(n²). For a dense graph, e approaches n²/2, and the two use similar space.
Worked example 10: choosing a representation
A social network has 1,000 users, and each has about 10 friends. Compare the space for an adjacency matrix and an adjacency list.
| Working | Reason |
|---|---|
| Matrix: 1,000 × 1,000 = 1,000,000 entries | One entry for every pair of users |
| Edges: 1,000 × 10 ÷ 2 = 5,000 | Each friendship is counted by both friends |
| List: 1,000 + 2 × 5,000 = 11,000 entries | One list per user, each edge stored twice |
| The list needs about 90 times less space | The graph is sparse, so a list suits it |
Uses of graphs
Graphs model road maps, computer networks, social networks, the links of the web and the states of a game. The traversal and shortest-path algorithms that work on them are taught in Graph traversal and shortest paths. This section is about storing them.
In a weighted graph, the matrix entry holds the weight instead of a 1, and a special value marks a missing edge. In the adjacency list, each neighbour is stored with its weight, as in B: A 4, C 1, D 5. For an undirected graph, the matrix is symmetric: the entry for A to B always equals the entry for B to A.
Graphs are dynamic in the same way as linked lists. Adding a node or an edge to an adjacency list only means adding to a list. Adding a node to a matrix means building a bigger grid, which is another reason lists suit graphs that change.
A tree is a graph too, but with no cycles, so a tree with n nodes always has exactly n − 1 edges. That makes trees very sparse, and they are almost always stored with pointers rather than as a matrix.
Check yourself. An undirected graph has 6 nodes and 7 edges. How many entries does its adjacency matrix have, and how many neighbour entries does its adjacency list hold?
Show the answer
The matrix has 6 × 6 = 36 entries. Each of the 7 edges appears in the lists of both its ends, so the lists hold 2 × 7 = 14 neighbour entries in total.
Section 6
Trees and binary search trees
Trees
A tree is a connected graph with no cycles. One node is the root. Every other node has exactly one parent, and nodes with no children are leaves. A binary tree is a tree where each node has at most two children, a left child and a right child.
Trees model anything with a hierarchy: folders on a disk, the structure of a web page, a family tree or the moves in a game. They are also the basis of fast search structures.
A tree is usually stored with a record for each node, holding the key, a left pointer and a right pointer. A null pointer means that child is missing. In an exam, the nodes are often kept in an array, with each pointer holding the index of a child, exactly like a linked list with two pointers.
The depth of a node is the number of edges from the root down to it. The height of a tree is the number of levels, from the root to the deepest leaf. A tree of height h needs at most h comparisons to find any key.
Binary search trees
A binary search tree, or BST, keeps one rule at every node. Every key in the left subtree is smaller than the node's key, and every key in the right subtree is larger. That rule lets a search discard half of what is left at each step, if the tree is well balanced.
To insert a key, start at the root. If the key is smaller, go left; otherwise go right. Repeat until you reach an empty place, and put the new node there. To search, follow exactly the same path until you find the key or reach an empty place.
Common mistake: going right for smaller keys. In a binary search tree, smaller keys always go to the left and larger keys to the right. Mixing up the sides at one node breaks the ordering, so later searches take the wrong branch and fail.
Worked example 11: building and searching a BST
Insert 50, 30, 70, 20, 40, 60, 80 and 35 in that order, then search for 35.
| Working | Reason |
|---|---|
| 50 is the root; 30 goes left, 70 goes right | 30 is smaller than 50 and 70 is larger |
| 20 goes left of 30; 40 goes right of 30 | Compare with 50, then with 30 |
| 60 and 80 go left and right of 70; 35 goes left of 40 | 35 is smaller than 50, larger than 30, smaller than 40 |
| Search for 35: visit 50, 30, 40, 35 | Four comparisons; the tree's height is 4 |
Traversals
A traversal visits every node of a tree once. There are three standard orders, and each is easiest to describe recursively. They differ only in when the node itself is visited compared with its two subtrees.
- Pre-order: visit the node, then traverse the left subtree, then the right subtree.
- In-order: traverse the left subtree, visit the node, then traverse the right subtree.
- Post-order: traverse the left subtree, then the right subtree, then visit the node.
An in-order traversal of a binary search tree visits the keys in sorted order. Pre-order is used to copy a tree, because each parent comes before its children. Post-order is used to delete a tree, because each node is removed only after its children.
Common mistake: thinking a traversal lists the keys in the order they were inserted. None of the three traversals simply replays the insertion order. Each one follows the shape of the tree, so work through it node by node rather than copying the input list.
Worked example 12: the three traversals
Give the pre-order, in-order and post-order traversals of the tree from worked example 11.
| Working | Reason |
|---|---|
| Pre-order: 50, 30, 20, 40, 35, 70, 60, 80 | Each node comes before its subtrees |
| In-order: 20, 30, 35, 40, 50, 60, 70, 80 | Left, node, right gives sorted order |
| Post-order: 20, 35, 40, 30, 60, 80, 70, 50 | Each node comes after its subtrees |
| The root is first in pre-order and last in post-order | A quick check of both answers |
Deleting from a BST is harder than inserting. A leaf can simply be removed, and a node with one child can be replaced by that child. A node with two children is replaced by its in-order successor, the smallest key in its right subtree, which keeps the ordering rule true.
Balanced and unbalanced trees
The speed of a BST depends on its shape. If the keys arrive in a random order, the tree is usually bushy and shallow. If they arrive already sorted, every key goes right of the last, and the tree becomes a single long chain. Searching it is then no better than a linked list.
Derivation: the height of a balanced binary tree
A full binary tree of height h has 1 node at the top level, 2 at the next, then 4, and so on. Add the nodes at every level.
So a tree of height h holds at most 2^h − 1 keys. Turning this round gives the smallest height that can hold n keys.
A balanced tree of a million keys has height 20, so a search takes at most 20 comparisons, which is O(log n). A chain of a million keys could take a million, which is O(n).
Self-balancing trees, such as AVL trees and red-black trees, rearrange themselves after each insertion so that the height stays close to log n. You do not need to know how they work for the exam. You do need to know why they exist: to stop sorted input from turning a tree into a chain.
Check yourself. Keys 10, 20, 30, 40 and 50 are inserted into an empty BST in that order. What is the tree's height, and why?
Show the answer
The height is 5. Each key is larger than every key before it, so it always goes to the right. The tree becomes a single chain of five nodes, which is the worst possible shape.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Linked list | Nodes joined by pointers, starting at a head | Ali → Dev → Kim → Sam | Access O(n); insert or delete O(1) once found |
| Free list | A linked list of the unused nodes | free = 4 | Take nodes from it; return deleted nodes to it |
| Hash function | Turns a key into a slot number | 27 MOD 10 = 7 | Same key, same slot; spread keys evenly |
| Load factor | Items divided by slots | 7 ÷ 10 = 0.7 | Rehash into a bigger table when it gets high |
| Linear probing | On a collision, try the next slot | 28 moves to slot 0 | Search until the key or an empty slot |
| Chaining | Each slot holds a list of keys | Slot 8: 18, 28 | Never fills; keys stay in their home slot |
| Adjacency matrix | n × n grid of edges | Row A, column B | Space O(n²); edge check O(1) |
| Adjacency list | Each node lists its neighbours | A: B, C | Space O(n + e); suits sparse graphs |
| Binary search tree | Smaller keys left, larger keys right | Root 50, left 30 | Search O(log n) if balanced, O(n) if a chain |
| Tree traversals | Pre-order, in-order, post-order | In-order of a BST is sorted | Pre-order copies; post-order deletes |
Programming task
Programming task: a hash table with linear probing
Aim
Write a Python program that stores integer keys in a hash table using key MOD size and linear probing. It must find keys that have been moved by collisions, report missing keys correctly, and refuse to insert into a full table.
Design
A class HashTable holds a list of slots, all starting as None. The method insert hashes the key and probes forward, wrapping with MOD, until it finds an empty slot. The method search follows the same path, stopping when it finds the key or an empty slot.
Both methods count their probes, so the program can show how collisions slow it down. A probe counter that reaches the table size means every slot has been tried, so the table is full or the key is absent.
Code
class HashTable:
def __init__(self, size):
self.size = size
self.slots = [None] * size
def hash(self, key):
return key % self.size
def insert(self, key):
slot = self.hash(key)
for probes in range(1, self.size + 1):
if self.slots[slot] is None:
self.slots[slot] = key
return slot, probes
slot = (slot + 1) % self.size
raise OverflowError("table full")
def search(self, key):
slot = self.hash(key)
for probes in range(1, self.size + 1):
if self.slots[slot] is None:
return None, probes
if self.slots[slot] == key:
return slot, probes
slot = (slot + 1) % self.size
return None, self.size
table = HashTable(10)
for key in [27, 18, 29, 28, 39, 13, 16]:
print(key, table.insert(key))
print(table.search(39), table.search(19))
The search stops at the first empty slot, because an insertion would have used it. The wrap-around with MOD means keys near the end of the table can spill into the start, exactly as 28 and 39 do.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | insert 27 into an empty table | (7, 1) | A key with no collision |
| 2 | insert 28 after 27, 18 and 29 | (0, 3) | A collision that wraps round |
| 3 | insert 39 after those four keys | (1, 3) | A second wrap-around |
| 4 | search 39 in the finished table | (1, 3) | Finds a moved key |
| 5 | search 19 in the finished table | (None, 4) | A missing key stops at the empty slot 2 |
| 6 | insert 11 keys into a table of 10 | table full | The table refuses an overflow |
| 7 | search 13 in the finished table | (3, 1) | A key found in its home slot |
Evaluation
The program places and finds every key correctly, including those moved by collisions, and reports missing keys without searching the whole table. Test 6 shows that a full table is refused rather than looping for ever.
An improvement would rehash into a table twice the size when the load factor passes 0.7. Another would support deletion, using a marker so that searches do not stop early at a removed key.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State what the head pointer and a null pointer mean in a linked list.
Worked solution to Q1
The head pointer holds the address of the first node, where a traversal starts. A null pointer in a node means there is no next node, so it marks the end of the list.
Q2. Define a collision in a hash table and name two ways of dealing with one.
Worked solution to Q2
A collision happens when two different keys hash to the same slot. It can be dealt with by linear probing, which places the key in the next free slot, or by chaining, which keeps a list of keys in each slot.
Q3. Describe the order in which an in-order traversal visits a binary tree, and state what it gives for a binary search tree.
Worked solution to Q3
An in-order traversal visits the left subtree, then the node itself, then the right subtree, at every node. For a binary search tree, this visits the keys in ascending sorted order.
Rung 2: Application
Q4. Using the hash function "sum of character codes MOD 11", find the slot for DOG. The codes are D = 68, O = 79 and G = 71.
Worked solution to Q4
The total is 68 + 79 + 71 = 218. Then 11 × 19 = 209, which leaves a remainder of 9, so 218 MOD 11 = 9. DOG goes in slot 9.
Q5. Insert 15, 25, 8, 35 and 18 into a table of 10 slots, using key MOD 10 and linear probing. Give the final slot of each key.
Worked solution to Q5
Key 15 goes to slot 5. Key 25 hashes to 5, which is full, so it moves to 6. Key 8 goes to slot 8. Key 35 hashes to 5; slots 5 and 6 are full, so it goes to 7. Key 18 hashes to 8, which is full, so it goes to 9.
Q6. Insert 45, 25, 65, 15, 35, 55 and 75 into an empty BST in that order, then give its pre-order traversal.
Worked solution to Q6
The root is 45, with 25 on the left and 65 on the right. Keys 15 and 35 are the children of 25. Keys 55 and 75 are the children of 65. Pre-order visits each node before its subtrees: 45, 25, 15, 35, 65, 55, 75.
Q7. Give the post-order traversal of the tree in Q6.
Worked solution to Q7
Post-order visits both subtrees before the node. The left subtree gives 15, 35, 25, and the right subtree gives 55, 75, 65. The root comes last: 15, 35, 25, 55, 75, 65, 45.
Rung 3: Analysis
Q8. A hash table uses linear probing and has a load factor of 0.95. Explain why searches are slow, and what should be done.
Worked solution to Q8
At a load factor of 0.95, almost every slot is full and long clusters have formed. A search may probe many slots before finding the key or an empty slot. The table should be rebuilt at a larger size and every key rehashed.
Q9. A graph has 500 nodes and 600 undirected edges. Calculate the number of entries in an adjacency matrix and in an adjacency list, and say which to use.
Worked solution to Q9
The matrix has 500 × 500 = 250,000 entries. The list has one list per node and stores each edge twice, giving 500 + 2 × 600 = 1,700 entries. The graph is sparse, so the adjacency list should be used.
Q10. Explain why the order in which keys are inserted affects the time taken to search a binary search tree.
Worked solution to Q10
Random orders usually build a shallow, balanced tree, where a search halves what is left at each step, which is O(log n). Sorted orders build a single chain, so a search may visit every node, which is O(n).
Q11. A list is stored with head 1 and free 4. Ali is node 1 with next 3, and Dev is node 3 with next 0. Describe the pointer changes needed to insert Ben.
Worked solution to Q11
Take node 4 from the free list, store Ben, and move free to node 4's old pointer. Ben goes between Ali and Dev, so first set node 4's pointer to 3. Then set Ali's pointer, node 1, to 4.
Rung 4: Stretch
Q12. Calculate the smallest possible height of a binary search tree holding 1,000 keys.
Worked solution to Q12
A tree of height h holds at most 2^h − 1 keys. 2^9 − 1 = 511 is too few, but 2^10 − 1 = 1,023 is enough. So the smallest possible height is 10, meaning a search needs at most 10 comparisons.
Q13. Explain why removing a key from a hash table that uses linear probing can make other keys impossible to find.
Worked solution to Q13
A search stops at the first empty slot. If a key in the middle of a cluster is removed, its slot becomes empty. Keys placed after it by probing are then cut off, because a search stops at the gap and reports them missing.
Q14. Compare a doubly linked list with a singly linked list for deleting a node, given only a pointer to that node.
Worked solution to Q14
In a singly linked list, the previous node must be found by traversing from the head, which is O(n). In a doubly linked list, the node's own previous pointer gives it at once, so the deletion is O(1). The cost is an extra pointer in every node.
Exam practice
Exam technique and worked answer workshop
Pointer questions reward a careful table. Copy the data and pointer columns, then cross out and replace each value as it changes. Give the final head and free pointers, and check your answer by traversing the finished list from the head.
For hash tables, show each calculation, such as 28 MOD 10 = 8, and say which slots are probed. Marks are often given for the probes as well as the final slot.
For trees, draw the tree before giving a traversal. Mark each node with a small dot on its left for pre-order, underneath for in-order and on its right for post-order. Then trace round the outside of the tree, writing nodes as you pass their dots.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
A linked list is stored in an array. Head is 2. Node 0 holds Cat with next 3, node 1 holds Fox with next null, node 2 holds Ant with next 0, and node 3 holds Dog with next 1.
(a) Give the items in the order a traversal visits them. [2]
(b) State the value of the pointer that must change to delete Dog, and its new value. [2]
Mark scheme for exam question 1
- B1 traversal starts at node 2, Ant
- B1 Ant, Cat, Dog, Fox
- B1 the pointer of node 0, Cat, must change
- B1 its new value is 1, so Cat points to Fox
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
A linked list of names is stored in alphabetical order in a 6-node array. Head is 1 and free is 4. Node 0 holds Kim with next 2, node 1 holds Ali with next 3, node 2 holds Sam with next null, and node 3 holds Dev with next 0. Node 4 is free with next 5.
Describe the steps to insert Ben, giving the final values of every pointer that changes.
Mark scheme for exam question 2
- M1 take node 4 from the free list and store Ben in it
- A1 free becomes 5
- M1 traverse to find that Ben goes between Ali and Dev
- A1 node 4's pointer is set to 3
- A1 node 1's pointer, Ali's, is set to 4
Exam question 3 (5 marks · Paper 02 · about 6 minutes)
A hash table of 11 slots uses the hash function "sum of character codes MOD 11". The codes are A = 65, C = 67, D = 68, G = 71, O = 79 and T = 84.
(a) Calculate the slots for CAT and DOG. [3]
(b) Explain why ACT causes a collision, and why this is a weakness of the hash function. [2]
Mark scheme for exam question 3
- M1 CAT: 67 + 65 + 84 = 216 and DOG: 68 + 79 + 71 = 218
- A1 CAT goes in slot 7
- A1 DOG goes in slot 9
- B1 ACT has the same letters, so it also totals 216 and hashes to 7
- B1 adding codes ignores letter order, so every anagram collides
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
The keys 27, 18, 29, 28 and 39 are inserted in that order into an empty hash table of 10 slots, using key MOD 10 and linear probing.
(a) Give the slot in which each key is stored. [3]
(b) Describe how a search for 39 finds it. [2]
Mark scheme for exam question 4
- B1 27, 18 and 29 in slots 7, 8 and 9
- B1 28 in slot 0
- B1 39 in slot 1
- M1 39 hashes to 9; slots 9 and 0 hold other keys, so the search moves on
- A1 found in slot 1 after 3 probes
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
The keys 50, 30, 70, 20, 40, 60, 80 and 35 are inserted in that order into an empty binary search tree.
(a) Draw the tree. [2]
(b) Give the pre-order and post-order traversals. [2]
(c) List the nodes visited when searching for 65, and state the result. [2]
Mark scheme for exam question 5
- B1 root 50, with 30 on the left and 70 on the right
- B1 20 and 40 under 30, 60 and 80 under 70, and 35 left of 40
- B1 pre-order: 50, 30, 20, 40, 35, 70, 60, 80
- B1 post-order: 20, 35, 40, 30, 60, 80, 70, 50
- M1 the search visits 50, 70, 60
- A1 60 has no right child, so 65 is not in the tree
Exam question 6 (6 marks · Paper 01 · about 9 minutes)
A phone's contacts app must store thousands of names with their numbers. It must find a contact by name quickly, add new contacts, and show all contacts in alphabetical order. Discuss whether a linked list, a hash table or a binary search tree should be used.
Mark scheme for exam question 6
Level 3 (5–6 marks): a clear comparison of all three structures against all three needs, with the cost of each operation explained. The answer reaches a justified recommendation, possibly combining structures. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct comparison of at least two structures against at least two needs, with some explanation of cost. The recommendation is limited or not fully justified.
Level 1 (1–2 marks): some relevant points, such as that a hash table is fast, with little explanation. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- a linked list kept in order can be shown in alphabetical order by traversing it
- but finding a contact means traversing from the head, which is O(n) and slow for thousands of names
- a hash table finds a contact by name in about O(1), by hashing the name
- adding to a hash table is also about O(1), but it may need rehashing as it fills
- a hash table keeps no order, so showing contacts alphabetically needs a sort, O(n log n)
- a binary search tree finds and adds contacts in O(log n) if it stays balanced
- an in-order traversal of the tree lists every contact in alphabetical order
- names added already sorted would unbalance the tree, so a self-balancing tree is safer
- recommendation: a balanced binary search tree meets all three needs well
Annotated model answer: exam question 6
"A linked list kept in alphabetical order makes listing the contacts easy: a traversal from the head visits them in order. But finding one contact means following pointers from the head, which is O(n). With thousands of contacts that is slow." (Linked list, against two needs, with its cost.)
"A hash table hashes the name to a slot, so finding or adding a contact is usually O(1). However, it stores the names in no useful order. Showing them alphabetically would need a sort every time, which is O(n log n)." (Hash table, against all three needs.)
"A binary search tree keeps smaller names to the left and larger to the right. Searching and adding are O(log n) if the tree is balanced, and an in-order traversal lists the contacts alphabetically." (Tree, against all three needs.)
"If names were added in alphabetical order, the tree would become a chain and searching would fall to O(n). A self-balancing tree avoids this. A balanced binary search tree is the best single choice, because it is fast for every need." (Weakness, then a justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It compares every structure against every need, explains the costs and justifies its recommendation.
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
A directed graph has nodes P, Q, R and S, with edges P→Q, P→R, Q→S and R→S.
(a) Complete an adjacency list for the graph. [2]
(b) Give one advantage of an adjacency matrix over an adjacency list. [1]
(c) State how many entries the adjacency matrix has. [1]
Mark scheme for exam question 7
- B1 P: Q, R
- B1 Q: S, R: S, S: none
- B1 a matrix checks whether one particular edge exists in one step, O(1)
- B1 4 × 4 = 16 entries
Annotated model answer: exam question 7
"(a) P: Q, R. Q: S. R: S. S: no neighbours." (Both marks: the edges only go one way, so S has an empty list.)
"(b) An adjacency matrix can check for an edge from one node to another in one step, by looking at a single cell." (The advantage, with the reason.)
"(c) The matrix has a row and a column for each of the 4 nodes, so 4 × 4 = 16 entries." (The count, with working.)
Exam question 8 (5 marks · Paper 01 · about 7 minutes)
(a) Explain why chaining avoids the clustering that affects linear probing. [2]
(b) A hash table of 8 slots holds 6 keys. Calculate its load factor. [1]
(c) Explain why the table must be rehashed, not just copied, when it is enlarged to 16 slots. [2]
Mark scheme for exam question 8
- B1 in chaining each key stays in its home slot, in that slot's list
- B1 so keys never spill into neighbouring slots to form runs of full slots
- B1 6 ÷ 8 = 0.75
- B1 each key's slot depends on the table size, through key MOD size
- B1 with 16 slots most keys hash to different slots, so each key must be hashed again
Connections
Synoptic link
These structures underpin much of the rest of the course. Graph traversal and shortest paths runs breadth-first search, depth-first search and Dijkstra's algorithm on the graphs stored here. Searching and sorting algorithms explains the binary search that a binary search tree imitates, and the in-order traversal is a way of sorting.
In Databases and normalisation, indexes are often built as trees or hash tables, so that a record can be found without reading the whole file. Subroutines and recursion explains why tree traversals are so neatly written as recursive subroutines.
Synoptic question 1. A database index is a balanced binary search tree of 1,000,000 keys. Each comparison takes 2 microseconds. Estimate the worst-case search time, and compare it with a linear search of an unsorted list.
Answer to synoptic question 1
A balanced tree of a million keys has a height of about 20, since 2^20 is just over a million. A search takes at most 20 × 2 = 40 microseconds. A linear search may take 1,000,000 × 2 = 2,000,000 microseconds, which is 2 seconds.
Recap
Recap and next step
- A linked list joins nodes with pointers from a head to a null; access is O(n), but inserting or deleting once the place is found is O(1).
- In an array, unused nodes form a free list; insert by setting the new node's pointer first, and delete by re-pointing the previous node.
- A hash function turns a key into a slot, often key MOD size; collisions are unavoidable, and the load factor shows how full the table is.
- Linear probing tries the next slot and forms clusters; chaining keeps a list in each slot. Searches must follow the same path as insertions.
- A graph is stored as an adjacency matrix, with O(n²) space, or an adjacency list, with O(n + e) space, which suits sparse graphs.
- A binary search tree keeps smaller keys left and larger right; in-order traversal gives sorted order, and a balanced tree searches in O(log n).
Next chapter: Boolean algebra and logic circuits turns to the hardware, building the circuits that every one of these structures finally runs on.
For your exam board
OCR A Level Computer Science (H446): this chapter covers linked lists, graphs, trees, binary search trees and hash tables in section 1.4.2, Data structures, in Component 01, Computer systems. Traversing these structures, including tree traversals, is in section 2.3.1, Algorithms, in Component 02.
AQA A Level Computer Science (7517): graphs and their representations, trees and binary trees, hash tables and the tree traversals appear in the fundamentals of data structures and the fundamentals of algorithms sections, assessed on Paper 1. Linked lists are expected as an implementation of other structures.