Sub topic 8
When Brute Force Is Good Enough to Ship
This chapter assumes you can estimate a brute-force cost in Big-O terms and turn that into a rough operation count, as covered in the earlier chapter on estimating cost. It also assumes you can read basic Python.
Engineers often treat brute force as a draft that must always be replaced. Sometimes it should be. Often it should not. If the inputs are small and will stay small, the exhaustive solution is usually the best one you can ship. It is short, easy to check, and hard to break.
The decision criteria
Ask these questions before you optimize:
- Is the input size bounded, and by what? A bound that comes from the domain, such as 12 months, 9 cells in a row, or 30 people on a team, is reliable. A bound that is only "what we have today" is not.
- How often does the code run? A nightly batch job that takes 2 seconds is fine. The same work in a request handler called 10,000 times per second is not.
- What does a bug cost? In billing, scheduling, or anything safety-related, a simple solution you can obviously trust has real value.
- Who maintains it? A clever algorithm that only one person understands costs something every time someone else has to change it.
The table below gives rough limits for plain Python, which manages about 10^7 simple operations per second. Compiled languages can handle roughly 10 to 50 times more.
| Complexity | Largest n for about 1 second in Python | Typical brute force |
|---|---|---|
| O(n^2) | about 3,000 | all pairs |
| O(n^3) | about 200 | all triples |
| O(2^n · n) | about 18–20 | all subsets |
| O(n!) | about 9–10 | all orderings |
Make the assumption explicit
The main risk of shipped brute force is silent growth. Data that held 50 rows last year holds 50,000 this year, and an O(n^2) loop that once took a millisecond now takes 40 minutes. You can defend against this by putting the bound in the code and failing loudly when it is exceeded.
import itertools
import math
# Domain bound: a warehouse floor has at most 1,000 charging docks.
MAX_POINTS = 1000
def closest_pair_distance(points):
"""Smallest distance between any two points. O(n^2) by design."""
if len(points) > MAX_POINTS:
raise ValueError(
f"expected at most {MAX_POINTS} points, got {len(points)}; "
"replace with a divide-and-conquer algorithm"
)
best = math.inf
for (x1, y1), (x2, y2) in itertools.combinations(points, 2):
best = min(best, math.hypot(x1 - x2, y1 - y2))
return best
print(closest_pair_distance([(0, 0), (3, 4), (1, 1)])) # 1.4142135623730951At 1,000 points this checks about 500,000 pairs, which takes well under a second. The O(n log n) divide-and-conquer version is around 60 lines long, has several tricky edge cases, and saves nothing users would notice at this scale.
Common mistakes
- Optimizing for imagined scale. Writing a hash-based or dynamic-programming solution for a list that can never hold more than 20 items adds risk and saves nothing.
- Trusting "small for now". If no rule or domain fact caps the input, assume it will grow.
- Ignoring the call count. A cost estimate covers one call. Multiply it by how often the code runs per request or per job.
- Forgetting the constant factor. Each step of O(n^2) in Python, such as building tuples or calling functions, can cost 50 to 100 nanoseconds or more. Benchmark at the bound instead of guessing.
Exercise
A scheduling tool assigns up to 8 meeting rooms to 8 teams and picks the assignment with the lowest total walking distance by trying every permutation. It runs once when a manager clicks "Optimize". Should you ship the brute-force version? What guard would you add?
Show answer
Yes. 8! = 40,320 assignments, each scored in about 8 steps, gives roughly 320,000 operations. That takes well under a second in Python, and the code runs only when a manager clicks the button. Add a check that raises an error if there are more than about 9 rooms or teams, because 11! is already about 40 million assignments. The error message should name an alternative, such as the Hungarian algorithm.
Exercise
An endpoint compares every pair of a user's saved addresses to find duplicates. Users have 3 addresses on average, but there is no limit. Is brute force acceptable?
Show answer
Not as it stands. The average is small, but nothing caps the number of addresses, and the endpoint serves live traffic. You can either enforce a product limit, such as 100 addresses, and keep the O(n^2) loop behind a guard, or normalize each address and group them with a dictionary in O(n).