Edexcel International Advanced Level Computer Science, point 15.1.1
Definition
A problem-solving technique is a general strategy for designing an algorithm. Different problems suit different techniques. You must understand each, choose a suitable one for a problem, and trace algorithms (Unit 3). In Unit 4 you use them in code.
Function and why needed
Knowing the techniques lets you recognise a problem type (10.1.3) and choose a method that is correct and efficient enough, instead of starting from nothing.
a. Brute force (exhaustive search)
Try every possible solution and check each one.
- Characteristics: simple, always finds a correct answer if one exists (the best one too, if you compare them all), but often very slow, since the number of possibilities grows fast.
- Example: cracking a 4-digit PIN by trying 0000 to 9999 ( tries), or finding two numbers in a list that add to a target by checking every pair.
def pair_with_sum(numbers, target):
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
return numbers[i], numbers[j]
return None
print(pair_with_sum([3, 8, 11, 15], 19)) # (8, 11)
- Benefits: easy to write and to prove correct, and fine for small problems.
- Drawbacks: impractical for large inputs (a 12-character password has billions of billions of possibilities, and trying every route through 20 towns is , about ).
b. Divide and conquer
Split the problem into smaller sub-problems of the same type, solve each (usually recursively), and combine the answers.
- Examples: binary search (5.2.2), merge sort (15.2.1), quick sort (15.2.2).
- Characteristics: sub-problems are independent, the work is reduced rapidly (often ), and it suits parallel processing (11.1.4).
- Benefits: much faster than brute force, natural recursion.
- Drawbacks: recursion overhead and stack use, and the combine step can be costly.
c. Greedy algorithms
At each step, choose the option that looks best right now, and never go back. Make a locally best choice hoping to reach a good overall answer.
Example: giving change with coins 25, 10, 5, 1: take the largest coin that fits.
def greedy_change(amount, coins):
result = []
for coin in sorted(coins, reverse=True):
while amount >= coin:
result.append(coin)
amount -= coin
return result
print(greedy_change(63, [25, 10, 5, 1])) # [25, 25, 10, 1, 1, 1]
Does greedy always work? No. With coins {1, 3, 4} and amount 6: greedy gives 4 + 1 + 1 (3 coins), but the best is 3 + 3 (2 coins).
print(greedy_change(6, [4, 3, 1])) # [4, 1, 1] (not optimal)
- Characteristics: fast and simple, no backtracking, uses local information.
- Benefits: efficient (often or better), and optimal for some problems (Dijkstra's shortest path, 15.2.3, Huffman coding, minimum spanning trees).
- Drawbacks: may give a non-optimal answer, and each problem needs checking that greedy is valid.
d. Heuristics
A rule of thumb that finds a good (not necessarily the best) solution in reasonable time, when finding the perfect answer is too slow (2.2.2 in other courses).
- Example: nearest neighbour for the travelling salesman problem: always go to the closest unvisited town. A* uses a heuristic estimate to guide its search (15.2.3).
- Characteristics: fast, approximate, no guarantee of optimality, based on experience or domain knowledge.
- Benefits: makes hard (intractable) problems solvable.
- Drawbacks: the answer may be poor, and may fail on unusual inputs.
e. Backtracking
Build a solution step by step. If a step leads to a dead end, undo it (backtrack) and try another.
- Examples: solving a maze, Sudoku, the eight queens problem, finding a path in a graph.
- Characteristics: explores a tree of choices depth first, and abandons a branch as soon as it can't succeed (pruning), so it is faster than pure brute force. Often written recursively.
def solve_subset(items, target, chosen=()):
if sum(chosen) == target:
return chosen
if sum(chosen) > target or not items:
return None # dead end: backtrack
# choice 1: include the first item
result = solve_subset(items[1:], target, chosen + (items[0],))
if result is not None:
return result
# choice 2 (after backtracking): leave it out
return solve_subset(items[1:], target, chosen)
print(solve_subset([8, 6, 7, 5, 3], 16)) # (8, 5, 3)
- Benefits: finds a solution when one exists, avoids exploring hopeless branches.
- Drawbacks: can still be very slow in the worst case, and uses stack space.
f. Recursion
A subprogram that calls itself on a smaller version of the problem (5.1.3, 10.4.1). It is the mechanism behind divide and conquer and backtracking, and natural for trees.
g. Tracing algorithms
Following an algorithm step by step, with chosen data, to see what it does (5.1.2). A trace table records each variable's value after each step.
total = 0
for n in [4, 7, 2]:
if n > 3:
total = total + n
print(total)
n |
n > 3? |
total |
|---|---|---|
| (start) | 0 | |
| 4 | True | 4 |
| 7 | True | 11 |
| 2 | False | 11 |
Output: 11. Tracing is used to check an algorithm, find errors (9.3.1), and work out what an unknown algorithm does.
Comparing the techniques
| Technique | Idea | Optimal? | Speed | Example |
|---|---|---|---|---|
| Brute force | Try everything | Yes | Slowest | PIN cracking |
| Divide and conquer | Split, solve, combine | Yes | Fast | Merge sort |
| Greedy | Best choice now | Not always | Very fast | Making change |
| Heuristic | Rule of thumb | No guarantee | Fast | Nearest neighbour |
| Backtracking | Try, undo, retry | Finds a solution | Variable | Sudoku |
| Recursion | Self-calling | (a tool) | Variable | Tree traversal |
Worked example
Task: a courier must visit 5 addresses and return to the depot, keeping the distance short. Compare brute force, a heuristic and a greedy approach.
- Brute force: try every order of the 5 addresses: routes, and pick the shortest. Guaranteed best, and fine for 5 stops. For 20 stops, there are orders: impossible.
- Greedy / nearest neighbour (also a heuristic): go to the nearest unvisited address each time. Takes very little time even for 1000 stops, but the route may be noticeably longer than the best, since an early nearby choice can force a long trip later.
- Choice: brute force for 5 stops (exact), a heuristic for large numbers of stops (good enough and fast).
Exam tip: define each technique and give an example that suits it. Link the technique to the problem ("a greedy method suits making change with standard coins, but may not give the fewest coins with unusual coins"). Mention trade-offs between speed and guaranteeing the best answer. Be able to complete a trace table.
Check yourself
What is brute force, and what is its main drawback?
Trying every possible solution and checking each one; it is simple but becomes far too slow as the problem grows.
What is a greedy algorithm?
One that makes the best-looking choice at each step without reconsidering earlier choices.
Give an example where a greedy algorithm doesn't give the best answer
Making 6 from coins 1, 3 and 4: greedy gives 4 + 1 + 1 (three coins) but 3 + 3 (two coins) is better.
What does backtracking do when it reaches a dead end?
It undoes the last choice and tries a different option.
What is a heuristic?
A rule of thumb that gives a good, but not guaranteed best, solution quickly.