Skip to main content

Summary: Brute Force

Everything on one page, to review the chapter before moving on.

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 (Brute Force and Exhaustive Search).
  • 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 to measure other algorithms and an excellent testing oracle.
  • The other techniques of the course are ways of avoiding its work: splitting, choosing greedily, reusing subproblems, pruning and bounding.

At a glance​

ProblemBrute-force costBetter approach in the course
Searching an elementO(n)O(n)Binary search on sorted data, O(log⁡n)O(\log n)
Maximum pairwise productO(n2)O(n^2)Linear scan, O(n)O(n)
Sorting by definition (selection, bubble)O(n2)O(n^2)Quicksort, Mergesort, O(nlog⁡n)O(n \log n)
Computing ana^nO(n)O(n) multiplicationsDivide and conquer, O(log⁡n)O(\log n)
Matrix multiplicationO(n3)O(n^3)—
Sorting by trying every permutation until one is sortedO(n⋅n!)O(n \cdot n!)Mergesort, O(nlog⁡n)O(n \log n)

When brute force is the right choice​

  • The input is small and will stay small.
  • The algorithm runs once, and writing it quickly matters more than running it quickly.
  • You need a trusted reference to test a faster algorithm.
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.