Sub topic 1
Why Start with Brute Force
Brute force is a strategy that solves a problem by trying every possible candidate answer and keeping the ones that work. It makes no clever assumptions about the data, which means it rarely hides bugs. This chapter explains why a brute-force version is often the best first solution to write, even when you already expect to replace it.
Prerequisites
This tutorial assumes you can already do the following:
- Write functions, loops, and recursive functions in Python or a similar language.
- Use arrays, lists, and dictionaries (hash maps).
- Read Big-O notation at an introductory level, such as O(n) or O(n²).
What Brute Force Means
A brute-force algorithm has two parts:
- A way to generate every candidate solution.
- A way to check whether a candidate meets the problem's conditions.
Take the two-sum problem: given a list of numbers and a target, find two different positions whose values add up to the target. The candidates are all pairs of distinct indices. The check is whether the two values add up to the target.
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
print(two_sum_brute([3, 8, 1, 5], 9)) # (1, 2)
print(two_sum_brute([1, 2], 10)) # NoneYou can confirm the code is correct by reading it. Every pair is tried exactly once, so if a valid pair exists, the loops will find it.
Why Write It First
Writing the brute-force version first gives you several practical benefits.
| Benefit | What it gives you |
|---|---|
| Correctness baseline | A working answer you can trust before any optimization |
| Problem understanding | Forces you to state exactly what a valid answer looks like |
| Test oracle | Correct outputs you can compare against faster code |
| Optimization map | The slow parts show you where the wasted work is |
| Sometimes the final answer | For small inputs, it may already be fast enough |
Jumping straight to a clever solution mixes two hard tasks: understanding the problem and designing an efficient method. If the clever version gives a wrong answer, you can't tell whether you misread the problem or made a mistake in the optimization. A brute-force version separates those two tasks.
The Workflow
The rest of this tutorial follows one loop: get a correct answer, measure it against the input limits, and improve it only if it is too slow.
Common Mistakes
- Skipping it because it looks too slow. Its main job is to be correct. Speed comes in a later step.
- Writing a partial brute force. If the loops miss some candidates (for example,
jstarts ati + 2), you have lost the main reason for writing it, which is that it is obviously correct. - Deleting it after optimizing. Keep it in your test suite. It stays useful as a reference long after you've replaced it in production.
- Adding clever shortcuts too early. Each shortcut is an assumption that could be wrong. Keep the first version plain.
Exercise
You need a function that reports whether any three distinct positions in a list sum to zero. Describe the candidates and the check a brute-force solution would use, and give its time complexity.
Show answer
The candidates are all index triples i < j < k. The check is nums[i] + nums[j] + nums[k] == 0. Three nested loops try every triple once, which takes O(n³) time.
Exercise
A teammate's optimized solution and your brute-force solution return different answers on one input. Why is it usually safe to suspect the optimized version first?
Show answer
The brute force tries every candidate with a simple check, so you can verify its correctness by reading it. The optimized version depends on extra assumptions and more complex logic, so it is more likely to contain the bug. Still, check the brute force's loop bounds to make sure it covers every candidate.