Sub topic 1
Why Start with Brute Force
When you face a new algorithmic problem, it is tempting to go straight for the clever solution: the hash map trick, the dynamic programming table, the two-pointer sweep. This chapter argues for a different first move. Write the simplest solution that is obviously correct, the one that tries every possibility, and only then decide whether you need something faster. That simplest solution is called brute force, and it is a deliberate engineering choice rather than a sign of weakness.
This chapter defines brute force precisely, shows its general shape, explains what it gives you beyond a working answer, and covers the mistakes people make when they skip it or write it badly. Later chapters go deeper into each technique: defining search spaces, enumerating subsets and permutations, estimating cost, stress testing, and optimization.
Prerequisites
This chapter assumes you can already do the following:
- Write functions, loops, and simple recursion in Python or a similar general-purpose language.
- Use basic data structures: lists (arrays) and dictionaries (hash maps).
- Read Big-O notation at an introductory level, for example knowing that a double loop over
nitems is O(n²).
You do not need any background in algorithm design techniques. The examples use only the Python standard library.
What Brute Force Means
A brute-force algorithm solves a problem by systematically generating every candidate solution and checking each one. Every brute-force solution has three parts:
- Generate. List every candidate in the search space. The search space is the full set of things that could possibly be the answer, such as every pair of indices, every subset of items, or every ordering of cities.
- Test. For each candidate, check whether it satisfies the problem's conditions.
- Select. Return the first valid candidate, all of them, a count, or the best one according to some cost.
The word "systematically" matters. A brute-force solution is exhaustive: it does not skip candidates because they "probably" won't work. That exhaustiveness is what makes it trustworthy. If the generator really covers the whole search space and the test really checks the problem's conditions, the answer is correct by construction.
A generic template
The three parts can be written as one small function. The example below uses it to find the pair of positions whose values sum closest to 10.
from itertools import combinations
def brute_force_best(candidates, is_valid, cost):
best = None
for c in candidates: # generate
if not is_valid(c): # test
continue
if best is None or cost(c) < cost(best): # select
best = c
return best
nums = [4, 9, 1, 7, 3]
pairs = combinations(range(len(nums)), 2) # every pair i < j
best = brute_force_best(
pairs,
is_valid=lambda p: True,
cost=lambda p: abs(nums[p[0]] + nums[p[1]] - 10),
)
print(best) # (1, 2): nums[1] + nums[2] == 9 + 1 == 10You will rarely write brute force through a helper like this in practice, but the template makes the structure explicit. When a brute-force solution gives a wrong answer, the bug is almost always in one of these three parts: the generator misses candidates, the test checks the wrong condition, or the selection keeps the wrong one.
A concrete example: two-sum
The two-sum problem runs through this tutorial: given a list nums and a number target, return two distinct indices i and j with nums[i] + nums[j] == target, or None if no such pair exists.
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([2, 7, 11, 15], 9)) # (0, 1)
print(two_sum_brute([3, 3], 6)) # (0, 1)
print(two_sum_brute([1, 2, 3], 100)) # None
print(two_sum_brute([], 0)) # NoneThe search space is every pair of distinct indices with i < j. The test is the sum check. The selection rule is "return the first match." You can see by inspection that this covers every pair exactly once and that the function returns None only after checking all of them. It runs in O(n²) time, which may or may not be acceptable. The point is that you can trust it before you know.
Why Start Here
Brute force is often described as the slow option you write when you can't think of anything better. In practice it gives you several things a clever-first approach does not.
| Benefit | What it gives you |
|---|---|
| Correctness baseline | A solution you can verify by reading, with no hidden insight to get wrong |
| Problem clarification | Writing the generator and test forces you to state exactly what counts as an answer |
| Edge-case discovery | Empty input, duplicates, negatives, and "no answer" cases come up naturally |
| A shippable answer | For small inputs, brute force is often fast enough to be the final solution |
| A test oracle | A slow-but-correct version lets you check a fast version on thousands of random inputs |
| A map of wasted work | Repeated or pointless computation in the brute force points directly at optimizations |
It turns a vague problem into a precise one
Problem statements are often ambiguous. Can i equal j? If several pairs work, which one do you return? What if the list is empty? You cannot write the brute force without answering these questions, because the generator and the test have to encode them. For example, range(i + 1, len(nums)) makes the choice that indices must be distinct and unordered. Answering these questions early is cheap. Discovering them after you have built an optimized solution around the wrong assumption is expensive.
It gives you something correct to compare against
Optimized algorithms are where subtle bugs live: off-by-one errors in a sliding window, a hash map updated in the wrong order, a sort that destroys the original indices. A brute-force solution has very little room for such mistakes. Once you have it, you can run both versions on many small random inputs and compare their outputs. A later chapter builds this stress testing workflow in detail.
It is sometimes the final answer
If the input has at most 20 items, or the function runs once a day on a list of 50 records, an O(n²) or even O(2ⁿ) solution may finish in milliseconds. Replacing it with a cleverer algorithm adds code, risk, and review burden for no user-visible gain. Knowing how to estimate the cost, which is covered later, lets you make this call with numbers instead of instinct.
It shows you where to optimize
Look again at two_sum_brute. For each j, the inner loop re-scans earlier elements looking for the value target - nums[j]. That repeated scan is the waste. Remembering earlier values in a dictionary removes it and yields an O(n) solution. Most optimizations come from this kind of reading: write the exhaustive version, then ask which work it repeats or never needed to do.
The Brute-Force-First Workflow
The diagram below shows how brute force fits into solving a problem from start to finish.
Notice that the brute force is not thrown away when you optimize. It moves into the test suite, where it keeps checking the fast version as the code changes.
What Brute Force Is Not
Brute force is easy to confuse with nearby ideas. Being precise about the differences prevents a common class of bugs.
- Greedy algorithms are not brute force. A greedy algorithm makes one locally good choice at each step and never reconsiders. It explores a single path, not the whole space. It may be correct for some problems, but its correctness needs a proof. Brute force needs none.
- Heuristics are not brute force. "Try the 100 most promising candidates" is a heuristic. It can miss the answer.
- Inefficient code is not automatically brute force. A solution can be slow and still incomplete. Slowness is a side effect of exhaustiveness, not its definition.
- Pruned search is still exhaustive in effect. Backtracking skips candidates only when it can prove they cannot succeed. That keeps correctness intact and is covered in a later chapter.
Common Errors
These mistakes show up repeatedly in code reviews and interviews.
- Skipping brute force entirely. You jump to an optimized idea, spend time debugging it, and still have nothing to compare it with. Even when you are confident in the fast approach, a ten-line brute force usually pays for itself within the first bug.
- Enumerating the wrong space. Using
range(len(nums))forjinstead ofrange(i + 1, len(nums))allowsi == j, so[5]with target10wrongly returns(0, 0). Using ordered pairs when the problem wants unordered ones double-counts results in counting problems. - Testing the wrong condition. Checking
<where the problem says<=, or comparing values when the problem asks for indices. - Selecting incorrectly. Returning the first valid candidate when the problem asks for the best one, or overwriting a running best without comparing it first.
- Over-engineering the brute force. Adding small optimizations to the baseline makes it harder to verify and defeats its purpose. Keep it plain. Its job is to be obviously right.
- Assuming brute force is always too slow. Without estimating the actual cost against the input limits, you may spend an hour optimizing something that already runs in a fraction of a second.
Exercises
Exercise
Identify the generate, test, and select parts of twosumbrute.
Show answer
Generate: the two nested loops produce every pair of indices (i, j) with i < j. Test: the condition nums[i] + nums[j] == target. Select: return the first pair that passes the test, or None after all pairs have been checked.
Exercise
A colleague writes a "brute force" two-sum that only checks adjacent pairs (i, i + 1). Give an input where it returns None but a valid answer exists, and explain why this version is unsafe as a test oracle.
Show answer
nums = [1, 5, 2], target = 3. The adjacent pairs sum to 6 and 7, but nums[0] + nums[2] == 3, so (0, 2) is a valid answer. Because the function does not cover the full search space, it can agree with a fast solution that has the same blind spot. Stress tests would then pass even though both versions are wrong.
Exercise
If twosumbrute's inner loop were changed to range(len(nums)), what would it return for nums = [5] and target = 10, and why is that wrong?
Show answer
It would return (0, 0), because the pair i = j = 0 gives 5 + 5 = 10. The problem requires two distinct indices, so the correct answer is None. The generator was enumerating a larger search space than the problem allows.
Exercise
A list has 10,000 elements. Roughly how many pairs does twosumbrute check in the worst case, and what does that suggest about whether it might be fast enough?
Show answer
It checks n(n - 1)/2 pairs, about 5 × 10^7 for n = 10,000. That is borderline: in plain Python it may take several seconds, while in a compiled language it would likely finish well under a second. You need a cost estimate against the real time limit before deciding to optimize.