COMP5000 Algorithms – Revision Notes
COMP5000 Algorithms – Revision Notes
Built from the lecture slides and revision lecture (Week 17, Lecture 3). Priority order: recurrences → recursive algorithms → complexity classes → backtracking and correctness → graphs → first-half concepts.
1. Recursion basics
Every recursive function has three parts:
Termination (base) condition: stops the recursion.
Non-recursive work: what the function does itself in each call, written f(n).
Recursive calls: the function calling itself on smaller input.
Divide and conquer has three steps: 1. Divide the problem into smaller parts, 2. Delegate each part to a recursive call, 3. Combine the results.
2. Time complexity of recursion
Write the running time as a recurrence T(n), then solve it.
Step 1: write T(n).
r = number of recursive calls
c = how much the input shrinks per call (n/c if divided, n−k if subtracted)
f(n) = non-recursive work per call
So T(n) = r·T(n/c) + O(f(n)), or T(n) = r·T(n−k) + O(f(n))
Step 2: expand into levels. T(n) = f(n) + r·f(n/c) + r²·f(n/c²) + … + r^L·f(n/c^L), where L is the number of levels.
Step 3: decide the type by comparing the cost of the second level, r·f(n/c), with the first, f(n):
Type | Meaning | Answer |
|---|---|---|
Decreasing | each level costs less | T(n) = O(f(n)) |
Equal (or almost equal) | each level costs about the same | T(n) = O(L · f(n)) |
Increasing | each level costs more | T(n) = O(r^L), which becomes O(n^(log_c r)) when dividing |
Number of levels L:
Dividing by c: L = log_c n.
Subtracting k: L = n/k (so T(n−3) has n/3 levels; constants vanish in O-notation).
Worked examples from the lecture:
Recurrence | Type | Answer |
|---|---|---|
T(n) = 4T(n/4) + O(n) | equal, L = log₄n | O(n log n) |
T(n) = T(n−3) + O(n) | equal, L = n/3 | O(n²) |
T(n) = 2T(n/2) + O(n) | equal, L = log₂n | O(n log n) |
T(n) = 2T(n/2) + O(1) | increasing, 2^(log₂n) | O(n) |
T(n) = 2T(n/4) + O(n) | decreasing | O(n) |
T(n) = T(n−1) + O(n) | equal, L = n | O(n²) |
T(n) = 2T(n/3) + O(n²) | decreasing | O(n²) |
Recognising it from code: a loop of n steps inside gives f(n) = O(n); copying a sub-array of size n/2 also costs O(n); a single comparison costs O(1). Count the recursive calls, then see how the argument shrinks.
If stuck: draw the recursion tree and add up each level.
3. The recursive algorithms
Algorithm | Recurrence | Complexity |
|---|---|---|
Factorial | T(n) = T(n−1) + O(1) | O(n) |
Fibonacci, naive | T(n) = T(n−1) + T(n−2) + O(1) | exponential, about O(2ⁿ) |
Fibonacci, memoised | each value computed once | O(n) |
Exponentiation, slow (x · power(x, n−1)) | T(n) = T(n−1) + O(1) | O(n) |
Exponentiation, fast | T(n) = T(n/2) + O(1) | O(log n) |
Tower of Hanoi | T(n) = 2T(n−1) + O(1) | O(2ⁿ) |
Bubble sort | nested loops | O(n²) |
Mergesort | T(n) = 2T(n/2) + O(n) | O(n log n) in all cases |
Quicksort | see below | best O(n log n), worst O(n²) |
Fibonacci and memoisation. Naive Fibonacci recomputes the same values again and again (f(3) is calculated many times inside f(6)), so the recursion tree explodes. Memoisation stores each result the first time it is calculated and looks it up afterwards, so each f(k) is computed only once and the time drops to O(n). Pseudocode shape: if n is already in the memo, return it; otherwise compute from f(n−1) and f(n−2), store, return.
Fast exponentiation. To compute xⁿ, compute half = power(x, n/2) once, then return half·half (times x if n is odd). If you call power(x, n/2) twice you lose the saving and are back to O(n).
Tower of Hanoi. To move n disks: move n−1 disks to the spare peg, move the biggest disk, move n−1 disks onto it. Two recursive calls on n−1 give T(n) = 2T(n−1) + O(1), increasing, so O(2ⁿ). Minimum number of moves = 2ⁿ − 1 (1 disk: 1, 2: 3, 3: 7, 4: 15).
Mergesort. Split the array in half, sort each half recursively, merge the two sorted halves. Merging two sorted arrays takes O(n): repeatedly compare the front elements and take the smaller. Base case: an array of 0 or 1 elements is already sorted. Time is O(n log n) in best, average and worst cases. It needs extra O(n) memory for merging.
Quicksort. Pick a pivot, partition the other elements into those smaller than the pivot and those larger, then recursively sort both parts.
Best case: pivot splits the array roughly in half every time, T(n) = 2T(n/2) + O(n), so O(n log n).
Worst case: the pivot is always the smallest or largest element (for example an already sorted array when you always pick the first element), giving T(n) = T(n−1) + O(n), so O(n²).
4. Backtracking
Backtracking builds a solution one choice at a time. If a partial solution breaks a constraint, undo the last choice (backtrack) and try the next option.
N Queens: place N queens on an N×N board so none attack each other. Place one queen per row; for each column check it is safe (no queen in the same column or diagonal); if safe, place it and recurse to the next row; if no column works, backtrack to the previous row and move that queen.
Subset Sum: is there a subset of the numbers adding to a target? For each element, either include it or exclude it and recurse on the rest. Two recursive calls on n−1 gives T(n) = 2T(n−1) + O(1) = O(2ⁿ) in the worst case. Stop early when the target is reached or exceeded.
Both are exponential in the worst case. Pruning (backtracking early) makes them faster in practice but does not change the worst case.
Note: I have not seen your lecturer's slides for these two, so check Moodle for the exact pseudocode and wording.
5. Correctness by induction
A correctness proof for a recursive algorithm has the shape of proof by induction:
Base case: show the algorithm is correct for the smallest input (and that it stops).
Inductive hypothesis: assume the algorithm is correct for all inputs smaller than n.
Inductive step: show that, given the hypothesis, it is correct for input of size n.
Mergesort: base case, arrays of size 0 or 1 are sorted. Hypothesis: it sorts any array smaller than n correctly. Step: both halves are smaller, so by the hypothesis they come back sorted; merging two sorted arrays gives a sorted array (so merge must itself be correct).
Quicksort: base case, size 0 or 1. Step: everything left of the pivot is ≤ pivot, everything right is larger; both parts are smaller than n so the hypothesis says they are sorted; so left + pivot + right is sorted.
6. Decision problems and complexity classes
A decision problem has a Yes/No answer. Classes (informally, how you would show a problem belongs):
Class | Meaning | To show a problem is in it |
|---|---|---|
P | solvable in polynomial time | give a polynomial-time algorithm |
NP | a "Yes" answer can be verified in polynomial time | give a polynomial-time checker for a yes-solution |
co-NP | a "No" answer can be verified in polynomial time | give a polynomial-time checker for a no-solution |
EXP | solvable in exponential time | give an exponential-time algorithm |
NP-hard | at least as hard as every problem in NP | reduce a known NP-hard problem to it |
NP-complete | NP-hard and in NP | show both |
What we know: P is inside NP and inside co-NP; NP is inside EXP; whether P = NP is an open question. CIRCUIT-SAT (is there an input making the circuit output 1?) is in NP, and is the standard first NP-complete problem.
Reductions. If problem A can be reduced to problem B in polynomial time, then B is at least as hard as A. Example: finding the smallest element can be done with a loop in O(n), or by reducing to sorting in O(n log n); the reduction works but is slower, so sorting is harder than finding the minimum.
Direction matters: to prove a new problem X is NP-hard, reduce a known NP-hard problem to X. If X were easy, the known hard problem would be easy too, which we do not believe.
If a polynomial algorithm exists for any NP-hard problem, then every problem in NP can be solved in polynomial time.
7. Graphs (lower priority)
Representations: adjacency matrix (V×V table, O(V²) space, quick edge lookup); adjacency list (each node stores its neighbours, O(V + E) space); object model.
Traversals: depth-first uses a stack (or recursion) and goes as deep as possible first; breadth-first uses a queue and goes level by level. Unweighted shortest path uses BFS.
Minimum spanning tree (MST): connects all nodes with minimum total edge weight and no cycles. Prim: start from one node, repeatedly add the cheapest edge joining the tree to a new node. Kruskal: sort all edges by weight, add the cheapest edge that does not create a cycle.
Dijkstra: shortest paths from one start node to all others in a weighted graph with non-negative weights. Keep a distance (starts at infinity, 0 for start) and predecessor per node; repeatedly take the unvisited node with smallest distance (priority queue) and relax its neighbours (update distance if the path through it is shorter).
Other terms: path, cycle, DAG (directed acyclic graph), bipartite graph, graph isomorphism.
8. First-half concepts (quick facts)
Halting problem: no algorithm can decide, for every program and input, whether the program halts. Proved by contradiction (assume a halting-checker H exists, build a program that does the opposite of what H predicts for itself). Result of Turing, relating to Hilbert's Entscheidungsproblem.
Exponential growth quickly beats polynomial growth (the chess-board grains example: doubling per square). Polynomial algorithms are called efficient; exponential ones do not scale.
Moore's Law: computing power roughly doubled every couple of years, but exponential-time algorithms outrun any hardware gain.
Babylonian method: an iterative algorithm for square roots; the lectures use it to discuss testing versus proving correctness.
9. Exam tips
Read code carefully: find r, c, f(n) before choosing the type.
For "select all that apply", judge every option separately.
Short-answer output questions: trace the code by hand step by step, writing values as you go.
Keep Moodle slides open and search by keyword, but do not use external sites or AI during the quiz.