Brute Force and Exhaustive Search
Brute force is the most direct way to design an algorithm: solve the problem by doing exactly what its statement says, with no attempt to exploit its structure. To find an element, look at every position. To find the best combination, generate every combination and keep the best one. To check whether a text contains a word, try the word at every position of the text.
It is the starting point of algorithm design, for three reasons:
- it is usually easy to design and easy to get right;
- for many problems it is a perfectly reasonable solution, especially for small inputs;
- it is the reference against which every cleverer algorithm is measured and tested.
All the design techniques of the following chapters can be seen as ways of avoiding part of the work that brute force does.
- The difference between straightforward brute force and exhaustive search over combinatorial spaces.
- Two concrete examples: naive string matching () and exhaustive search over subsets ().
- Why exponential and factorial growth make exhaustive search impractical even with much faster hardware.
- When brute force is still the right choice: small inputs, baselines, and testing oracles for more complex algorithms.
Two flavors of brute force
The term covers two related ideas.
Straightforward algorithms
The first is simply the most obvious algorithm that follows the definition of the problem. Many of them have already appeared in the course:
- Sequential search: compare the element with every position of the array, .
- The maximum pairwise product computed by trying every pair of numbers, .
- Selection sort and bubble sort, which follow the definition of "sorted" directly, .
- Computing by multiplying by itself times, multiplications (divide and conquer does it in ).
- Matrix multiplication following the definition , .
These algorithms are often polynomial. They may be slow for large inputs, but they are usable.
Exhaustive search
The second idea applies to problems whose answer is a combinatorial object: a subset, a permutation, an assignment, a path. Exhaustive search generates every candidate in the space of possible solutions, checks each one against the constraints, and keeps the solution (or the best one). Its scheme is often called generate and test:
for each candidate c in the space of candidates:
if c satisfies the constraints:
process c // print it, count it, or compare it with the best so far
Typical spaces of candidates are:
| Problem | Candidates | Number of candidates |
|---|---|---|
| 0/1 knapsack, subset sum | All subsets of objects | |
| Task assignment | All permutations of tasks | |
| Traveling salesman (symmetric) | All tours through cities | |
| Magic square of side | All arrangements of numbers | |
| Passwords of length over an alphabet of size | All strings |
These numbers grow exponentially or factorially, and that is the real problem of exhaustive search.
Example: naive string matching
Problem. Given a text of length and a pattern of length , find the first position where occurs in .
The brute-force algorithm places the pattern at each position of the text, compares character by character, and moves the pattern one position to the right as soon as a character does not match:
public static int match(String text, String pattern) {
int n = text.length();
int m = pattern.length();
for (int i = 0; i <= n - m; i++) { // every possible position
int j = 0;
while (j < m && text.charAt(i + j) == pattern.charAt(j))
j++;
if (j == m) // the whole pattern matched
return i;
}
return -1; // not found
}
Analysis.
- Best case: the pattern is at position 0. The algorithm makes comparisons: .
- Worst case: at every position the mismatch is detected only at the last character of the pattern. For example, text
AAA...AABand patternAA...AB. There are positions with comparisons each: , which is when is small compared to . - Typical case: with ordinary text the mismatch usually appears at the first or second character, so the algorithm behaves almost linearly.
We measured the algorithm with a text of one million characters:
| Text and pattern | Character comparisons | Time |
|---|---|---|
| Random letters, pattern of 1,000 characters at the end | about 1.04 million (1.04 per position) | 3.5 ms |
Worst case AAA...AB, pattern of 1,000 characters | about 999 million | 0.37 s |
Worst case AAA...AB, pattern of 10,000 characters | about 9,900 million | 4.1 s |
The same algorithm is a thousand times slower on the adversarial input. Interestingly, Java's own String.indexOf uses essentially this brute-force method (heavily optimized by the virtual machine), and it showed the same behavior: about 4.6 s for the last row. It is fast for everyday texts, but not protected against the worst case. Algorithms such as Knuth-Morris-Pratt or Boyer-Moore guarantee by never re-examining characters of the text that have already been matched.
Example: exhaustive search over subsets
Problem. The 0/1 knapsack: given objects with weights and values and a capacity , choose objects to maximize the value without exceeding the capacity.
Exhaustive search generates the subsets. A simple way to enumerate them is to use the bits of an integer from to : bit set means "object is in the subset".
int bestValue = 0;
long bestMask = 0;
for (long mask = 0; mask < (1L << n); mask++) { // every subset
int weight = 0, value = 0;
for (int i = 0; i < n; i++)
if ((mask & (1L << i)) != 0) { // object i is in the subset
weight += w[i];
value += v[i];
}
if (weight <= W && value > bestValue) { // test: valid and better?
bestValue = value;
bestMask = mask;
}
}
With the instance used in the dynamic programming lesson (weights 6, 5, 5, values 8, 5, 5 and ), the 8 subsets are:
| Subset | Weight | Value | Valid? |
|---|---|---|---|
| none | 0 | 0 | yes |
| 1 | 6 | 8 | yes |
| 2 | 5 | 5 | yes |
| 3 | 5 | 5 | yes |
| 1, 2 | 11 | 13 | no |
| 1, 3 | 11 | 13 | no |
| 2, 3 | 10 | 10 | yes, best |
| 1, 2, 3 | 16 | 18 | no |
The algorithm is obviously correct: it looks at every possibility. Its cost is . In our measurements, a similar exhaustive search over the subsets of 28 numbers took about 28 seconds; with 40 numbers it would take about two days.
The same pattern works for permutations (generated as in the backtracking lesson), with candidates instead of .
How fast is "too slow"?
Assuming a computer that executes basic operations per second, the time needed for an algorithm with each growth rate is:
| 10 | 0.1 µs | 1 µs | 1 µs | 3.6 ms |
| 20 | 0.4 µs | 8 µs | 1 ms | 77 years |
| 30 | 0.9 µs | 27 µs | 1.1 s | years |
| 40 | 1.6 µs | 64 µs | 18 minutes | years |
| 50 | 2.5 µs | 125 µs | 13 days | years |
| 60 | 3.6 µs | 216 µs | 37 years | years |
Two conclusions follow:
- Polynomial brute force (, ) is often acceptable.
- Exponential and factorial brute force is only feasible for very small : about 30 to 40 for , and about 12 to 13 for . A computer a thousand times faster only adds about 10 to the feasible for , and 2 or 3 for .
For example, an exhaustive solution of the traveling salesman problem with 10 cities checks 181,440 tours, which is instantaneous. With 20 cities it would have to check about tours.
When brute force is the right choice
Brute force is not just a naive first attempt. It is the right tool when:
- The input is small, or the program runs only once. Ten seconds of computer time may be much cheaper than a day of programmer time.
- No better algorithm is known. For many NP-hard problems, the best exact algorithms are still exponential; they are refined versions of exhaustive search (see backtracking and branch and bound).
- Correctness matters more than speed. A brute-force solution is easy to verify, so it can serve as a reference.
- The work is easy to parallelize. The candidates of an exhaustive search are independent, so they can be split among many processors. This is what password-cracking tools do on graphics cards: an 8-character password of lowercase letters has candidates, which takes minutes. Every extra character multiplies that time, which is why long passwords are safe.
Brute force as a testing oracle
One of the most valuable uses of brute force in practice is testing clever algorithms. The technique is called stress testing (or differential testing):
- Write a brute-force solution that is obviously correct.
- Generate many random small inputs.
- Run both algorithms on each input and compare the results.
- When they differ, the input is a small, concrete counterexample that shows the bug.
This is how many errors in greedy and divide and conquer algorithms are found. For example, comparing a greedy coin-change algorithm with an exhaustive one quickly finds coin systems for which the greedy algorithm is not optimal (see greedy algorithms).
Beyond brute force
Every other paradigm of the course can be seen as a way of avoiding part of the work of brute force:
| Paradigm | What it avoids |
|---|---|
| Divide and conquer | Splits the problem into smaller independent subproblems whose solutions combine cheaply (fast exponentiation, mergesort, binary search). |
| Greedy algorithms | Makes one irrevocable choice per step and never considers the alternatives. Fast, but only optimal for some problems. |
| Dynamic programming | Solves each distinct subproblem only once and stores the result, instead of recomputing it in every candidate. |
| Backtracking | Builds candidates step by step and abandons a partial candidate as soon as it cannot succeed (pruning). |
| Branch and bound | Explores the most promising candidates first and discards those whose bound shows they cannot beat the best known solution. |
Other general techniques also reduce the cost of exhaustive search without changing its nature. A notable one is meet in the middle: to solve subset sum with numbers, split them into two halves, enumerate the sums of each half, sort one list, and for each sum of the other half look for its complement by binary search. The cost drops from to about . In our measurements, with 28 numbers this took 5 ms instead of 28 s, and with 40 numbers 0.6 s instead of the estimated two days.
Self-check
1. Two kinds. What is the difference between a straightforward algorithm and exhaustive search?
A straightforward algorithm applies the definition of the problem directly (for example, multiplying matrices with the definition), and is often polynomial. Exhaustive search generates every candidate solution of a combinatorial problem and tests each one, and is usually exponential or factorial.
2. String matching. Give a text and a pattern that force the naive string matching algorithm into its worst case.
Text AAAA...AAAB (many A's) and pattern AA...AB. At every position, all the A's of the pattern match and the mismatch is only found at the final B, so each of the positions costs comparisons.
3. Counting candidates. How many candidates does exhaustive search examine for the task assignment problem with 12 agents and 12 tasks? Is it feasible?
assignments, each evaluated in about 12 additions: roughly operations, a few seconds. Feasible, but with 15 agents it would already take hours, and with 20 more than a thousand years.
4. Faster hardware. An exhaustive algorithm of cost solves instances of size 40 in 18 minutes. What size can it solve in the same time on a computer 1,000 times faster?
About 50, since . A thousand-fold improvement in hardware only adds 10 to the feasible size.
5. Testing. Why is a brute-force algorithm useful even when we already have a faster one?
Because it is easy to trust, so it can be used as an oracle: comparing both algorithms on many small random inputs reveals bugs in the fast one, together with a small counterexample.
- Discarding brute force without looking at the input size. For small inputs it is often the best choice: simple and correct.
- Underestimating exhaustive search. There are subsets and permutations, not .
- Generating candidates twice or missing some. Exhaustive search is only correct if it visits every candidate exactly once.
Key ideas
- Brute force solves a problem in the most direct way, following its statement. Exhaustive search generates and tests every candidate of a combinatorial space.
- It is simple, general and easy to get right, and for small inputs it is often good enough.
- Exhaustive search over subsets costs and over permutations : only very small instances are feasible, and faster hardware barely helps.
- Brute force is the baseline for measuring other algorithms and an excellent testing oracle.
- The other paradigms of the course are ways of avoiding the work of brute force: splitting, choosing greedily, reusing subproblems, pruning and bounding.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.