Skip to main content

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.

What you will learn in this lesson
  • The difference between straightforward brute force and exhaustive search over combinatorial spaces.
  • Two concrete examples: naive string matching (O(n⋅m)O(n \cdot m)) and exhaustive search over subsets (O(2n)O(2^n)).
  • 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, O(n)O(n).
  • The maximum pairwise product computed by trying every pair of numbers, O(n2)O(n^2).
  • Selection sort and bubble sort, which follow the definition of "sorted" directly, O(n2)O(n^2).
  • Computing ana^n by multiplying aa by itself n−1n - 1 times, O(n)O(n) multiplications (divide and conquer does it in O(log⁡n)O(\log n)).
  • Matrix multiplication following the definition cij=∑kaikbkjc_{ij} = \sum_k a_{ik} b_{kj}, O(n3)O(n^3).

These algorithms are often polynomial. They may be slow for large inputs, but they are usable.

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:

ProblemCandidatesNumber of candidates
0/1 knapsack, subset sumAll subsets of nn objects2n2^n
Task assignmentAll permutations of nn tasksn!n!
Traveling salesman (symmetric)All tours through nn cities(n−1)!/2(n-1)!/2
Magic square of side nnAll arrangements of n2n^2 numbers(n2)!(n^2)!
Passwords of length kk over an alphabet of size ssAll stringssks^k

These numbers grow exponentially or factorially, and that is the real problem of exhaustive search.


Example: naive string matching​

Problem. Given a text TT of length nn and a pattern PP of length m≤nm \le n, find the first position where PP occurs in TT.

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
}
Naive string matching: the pattern ABAC is tried at every position of the text until it matchestextABAABABACABA01234567891011ABACi = 04 comparisonsABACi = 11 comparisonABACi = 22 comparisonsABACi = 34 comparisonsABACi = 41 comparisonABACi = 5match!green: equal · red: first mismatch, then shift one position · 16 comparisons in total
Naive string matching of ABAC in ABAABABACABA. At each position the pattern is compared character by character; at the first mismatch it moves one position to the right. Here 16 comparisons find the match at position 5.

Analysis.

  • Best case: the pattern is at position 0. The algorithm makes mm comparisons: O(m)O(m).
  • Worst case: at every position the mismatch is detected only at the last character of the pattern. For example, text AAA...AAB and pattern AA...AB. There are n−m+1n - m + 1 positions with mm comparisons each: O((n−m+1)⋅m)O((n - m + 1) \cdot m), which is O(n⋅m)O(n \cdot m) when mm is small compared to nn.
  • 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 patternCharacter comparisonsTime
Random letters, pattern of 1,000 characters at the endabout 1.04 million (1.04 per position)3.5 ms
Worst case AAA...AB, pattern of 1,000 charactersabout 999 million0.37 s
Worst case AAA...AB, pattern of 10,000 charactersabout 9,900 million4.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 O(n+m)O(n + m) 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 wiw_i and values viv_i and a capacity WW, choose objects to maximize the value without exceeding the capacity.

Exhaustive search generates the 2n2^n subsets. A simple way to enumerate them is to use the bits of an integer from 00 to 2n−12^n - 1: bit ii set means "object ii 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 W=10W = 10), the 8 subsets are:

SubsetWeightValueValid?
none00yes
168yes
255yes
355yes
1, 21113no
1, 31113no
2, 31010yes, best
1, 2, 31618no
The 2 to the n subsets of three objects as the leaves of a binary tree of decisionstake 1skip 1{1,2,3}{1,2}{1,3}{1}{2,3}{2}{3}∅object 1: in or out?object 2: in or out?object 3: in or out?each level doubles the number of nodes: 2³ = 8 subsets for n = 3
Exhaustive search over subsets: each object is either taken or skipped, so three objects give 2³ = 8 subsets, the leaves of this tree. Each additional object doubles the number of leaves.

The algorithm is obviously correct: it looks at every possibility. Its cost is O(n⋅2n)O(n \cdot 2^n). 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 n!n! candidates instead of 2n2^n.


How fast is "too slow"?​

Assuming a computer that executes 10910^9 basic operations per second, the time needed for an algorithm with each growth rate is:

nnn2n^2n3n^32n2^nn!n!
100.1 µs1 µs1 µs3.6 ms
200.4 µs8 µs1 ms77 years
300.9 µs27 µs1.1 s8×10158 \times 10^{15} years
401.6 µs64 µs18 minutes3×10313 \times 10^{31} years
502.5 µs125 µs13 days104810^{48} years
603.6 µs216 µs37 years3×10653 \times 10^{65} years

Two conclusions follow:

  • Polynomial brute force (n2n^2, n3n^3) is often acceptable.
  • Exponential and factorial brute force is only feasible for very small nn: about 30 to 40 for 2n2^n, and about 12 to 13 for n!n!. A computer a thousand times faster only adds about 10 to the feasible nn for 2n2^n, and 2 or 3 for n!n!.

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 6×10166 \times 10^{16} 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 268≈2×101126^8 \approx 2 \times 10^{11} 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):

  1. Write a brute-force solution that is obviously correct.
  2. Generate many random small inputs.
  3. Run both algorithms on each input and compare the results.
  4. 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:

ParadigmWhat it avoids
Divide and conquerSplits the problem into smaller independent subproblems whose solutions combine cheaply (fast exponentiation, mergesort, binary search).
Greedy algorithmsMakes one irrevocable choice per step and never considers the alternatives. Fast, but only optimal for some problems.
Dynamic programmingSolves each distinct subproblem only once and stores the result, instead of recomputing it in every candidate.
BacktrackingBuilds candidates step by step and abandons a partial candidate as soon as it cannot succeed (pruning).
Branch and boundExplores 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 nn numbers, split them into two halves, enumerate the 2n/22^{n/2} 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 O(2n)O(2^n) to about O(2n/2⋅n)O(2^{n/2} \cdot n). 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 n−m+1n - m + 1 positions costs mm 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?

12!=479,001,60012! = 479{,}001{,}600 assignments, each evaluated in about 12 additions: roughly 6×1096 \times 10^9 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 2n2^n 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 210=1024≈10002^{10} = 1024 \approx 1000. 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.

Common mistakes
  • 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 2n2^n subsets and n!n! permutations, not n2n^2.
  • 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 O(2n)O(2^n) and over permutations O(n!)O(n!): 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.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.