Sub topic 8
When Brute Force Is Good Enough to Ship
Earlier chapters treated brute force as a starting point: a correct baseline you write first and then replace. Sometimes the replacement never needs to happen. This chapter covers how to decide, with evidence, that the brute-force version is the version you ship, and how to ship it without leaving a trap for the next person who touches the code.
This chapter assumes you can estimate a brute-force running time from input limits (covered in "Will It Run in Time?") and that you know how to enumerate pairs, subsets, and permutations in Python.
The Real Question Is Cost, Not Elegance
An optimized algorithm costs something to build. It takes longer to write and longer to review. It has more places for bugs to hide, and it usually needs more explanation for whoever maintains it. You pay those costs to buy speed. If the brute-force version already runs fast enough on every input the program will ever see, the extra speed buys nothing, and you still pay the costs.
So the decision depends on three questions:
- What is the largest input this code will realistically receive, and what enforces that limit?
- How long does the brute force take on that largest input, measured and not guessed?
- How often does it run, and who is waiting for it?
If the answers are "small, enforced, fast, and rarely or off the critical path," brute force is a legitimate final answer.
Situations Where Brute Force Wins
| Situation | Why brute force fits | Example |
|---|---|---|
| Input size fixed by the domain | The worst case cannot grow | Checking all 2^7 combinations of 7 feature flags |
| One-off or offline scripts | Runtime of minutes is acceptable | A data migration run once overnight |
| Correctness is expensive to get wrong | Simple code is easier to verify | Validating the rules of a financial settlement |
| Small n inside a larger algorithm | Low overhead beats better asymptotics | Insertion sort on short runs inside a merge sort |
| Prototype or spike | Learning the problem matters more than speed | Exploring whether a scheduling rule is even feasible |
| No known efficient algorithm | Exhaustive search may be the best available | Exact traveling salesman on 10 cities |
The last row deserves attention. For NP-hard problems such as subset sum or exact traveling salesman, no algorithm is known that runs in polynomial time in the worst case. Dynamic programming or branch-and-bound can push the limit further, but for small instances a clean exhaustive search is often the most honest solution.
Why Small n Favors Simple Code
Big-O notation hides constant factors, and at small sizes those constants dominate. An O(n log n) algorithm that allocates a hash table, sorts, or recurses has fixed overhead on every call. An O(n²) double loop over a contiguous list has almost none. For n around 10 to 50, the "slower" algorithm often finishes first.
Production libraries rely on this. CPython's list.sort (Timsort) uses binary insertion sort, an O(n²) method, on short runs before merging them. Many introsort implementations in C++ standard libraries switch to insertion sort below a cutoff of about 16 elements. These hybrids are brute force on purpose: the cheap method handles the small pieces and the asymptotically better method handles scale.
You can apply the same idea in your own code:
import itertools
SMALL_INPUT = 32
def min_gap(values):
"""Smallest absolute difference between any two values."""
if len(values) < 2:
raise ValueError("need at least two values")
if len(values) <= SMALL_INPUT:
# Brute force: check every pair. Obviously correct, low overhead.
return min(abs(a - b) for a, b in itertools.combinations(values, 2))
# Larger inputs: after sorting, the closest pair is adjacent.
s = sorted(values)
return min(b - a for a, b in zip(s, s[1:]))
print(min_gap([10, 3, 25, 7, 19])) # 3 (7 - 3 = 4, 10 - 7 = 3)
print(min_gap(list(range(0, 1000, 5)))) # 5The brute-force branch also acts as a built-in reference: you can compare both branches against each other on inputs of size 32 or less to check the sorted branch.
Measure the Worst Case Before You Commit
An estimate from the previous chapter tells you whether brute force is plausible. Before you ship it, measure the actual worst case on the actual hardware class it will run on. Choose an input that forces the full search, such as one with no solution, so nothing exits early.
import itertools
import random
import time
def best_order(durations, deadlines):
"""Ordering of tasks that minimizes total lateness, by trying every ordering."""
n = len(durations)
best_cost, best_perm = None, None
for perm in itertools.permutations(range(n)):
t = 0
cost = 0
for i in perm:
t += durations[i]
cost += max(0, t - deadlines[i])
if best_cost is None or cost < best_cost:
best_cost, best_perm = cost, perm
return best_perm, best_cost
def time_worst_case(n, repeats=3):
durations = [random.randint(1, 10) for _ in range(n)]
deadlines = [random.randint(1, 30) for _ in range(n)]
best = float("inf")
for _ in range(repeats):
start = time.perf_counter()
best_order(durations, deadlines)
best = min(best, time.perf_counter() - start)
return best
for n in range(5, 10):
print(f"n={n}: {time_worst_case(n):.3f} s")Every permutation is visited regardless of the data, so any random input is a worst case here. On a typical laptop you will see the time grow by roughly a factor of n at each step: milliseconds at n=7 and a few seconds at n=9. That curve is the evidence you need. If the product never schedules more than 8 tasks at once, this code is fine. If it might schedule 12, it is not, because 12! is about 479 million orderings.
Ship It With a Guard
A brute-force solution that is fast enough today depends on an assumption about input size. Unwritten assumptions break quietly. Someone raises a limit in a config file, a customer imports a larger dataset, and a request that took 20 ms now takes an hour. Nothing fails loudly; the system just stalls.
Turn the assumption into code:
import itertools
MAX_TASKS = 8 # 8! = 40,320 orderings; measured under 0.1 s worst case.
def best_order_guarded(durations, deadlines):
n = len(durations)
if n != len(deadlines):
raise ValueError("durations and deadlines must have the same length")
if n > MAX_TASKS:
raise ValueError(
f"best_order supports at most {MAX_TASKS} tasks (got {n}); "
"exhaustive search grows as n!"
)
best_cost, best_perm = None, None
for perm in itertools.permutations(range(n)):
t = 0
cost = 0
for i in perm:
t += durations[i]
cost += max(0, t - deadlines[i])
if best_cost is None or cost < best_cost:
best_cost, best_perm = cost, perm
return best_perm, best_cost
print(best_order_guarded([3, 2, 4], [4, 6, 9])) # ((0, 1, 2), 0)The guard does three jobs. It makes the limit visible to readers, and it fails fast with a clear message instead of hanging. It also records why the limit exists, so a future maintainer knows the guard is not arbitrary and has to be replaced along with the algorithm, not just raised.
Add a test that runs the function at exactly MAX_TASKS with a time budget. If a later change slows the inner loop, that test catches it.
How Brute Force Goes Wrong in Production
The failures are predictable, which makes them preventable.
- Limits that drift. The input was small when the code was written. Product growth changed that. A guard plus a comment that records the measurement prevents silent drift.
- Hidden nesting. A brute-force loop calls a helper that is itself linear, such as
x in some_list. An O(n²) design becomes O(n³) without anyone noticing. Profile the whole call, not just the outer loop. - Multiplied call sites. A 50 ms brute force is fine once per request and terrible when called once per row of a 10,000-row report. Check how often the function runs, not only how long one call takes.
- Benchmarks that are too easy. Testing on inputs where a solution appears early hides the full-search cost. Benchmark the no-solution case.
- Different hardware. A laptop benchmark can overstate the speed of a shared CI runner or a small container by several times. Leave headroom, such as a factor of 10 below your time budget.
A Decision Flow
Making the Case in a Review
When you ship brute force, reviewers will reasonably ask why you did not optimize. Answer with the facts in one or two sentences: the bound, the measurement, and the guard. For example: "Input is capped at 8 tasks by the scheduling UI; worst case is 40,320 orderings, measured at 60 ms; the function raises above 8." That gives a reviewer something concrete to check, which "it's fast enough" does not. The final chapter covers this kind of explanation in more detail.
Exercise
A function checks every pair of user accounts for duplicate email addresses using a double loop. It runs in a nightly batch job on 2,000 accounts and takes 1.5 seconds. The company expects 5,000,000 accounts within two years. Should you ship the brute force? Justify with numbers.
Show answer
Not without a plan. The cost is O(n²): going from 2,000 to 5,000,000 accounts multiplies the pair count by (2500)² = 6.25 million, so 1.5 s becomes about 9.4 million seconds, which is over 100 days. That breaks even a nightly job. Shipping it now is defensible only with a guard that fails clearly above a measured limit, such as about 50,000 accounts (625 times the work, around 16 minutes). A hash-set pass in O(n) is simple enough that writing it now is likely the better choice.
Exercise
An API endpoint accepts a JSON list of items and runs subsetsumexists (2^n subsets) on it. Tests use lists of 10 items and finish in 2 ms. What is the risk, and what minimal change makes the endpoint safe to ship?
Show answer
The input size is controlled by the caller, so a request with 40 items forces about 10^12 subsets and ties up a worker indefinitely, which is a denial-of-service risk. The minimal fix is to validate the list length at the API boundary, before calling the function, against a limit chosen from measurement (for example, reject requests with more than 20 items, about one million subsets), and return a clear client error above it.
Exercise
Your hybrid min_gap function uses brute force for up to 32 values. Benchmarks show the pair loop is faster than sort-and-scan up to 60 values on your servers. Should you change the cutoff to 60, and what else should you do before or after changing it?
Show answer
Raising the cutoff toward the measured crossover is reasonable, but leave some margin (for example, 48), because hardware and Python versions vary and the gain near the crossover is small. Either way, add a test comparing both branches on random inputs around the cutoff size, so the two code paths are checked against each other and stay consistent.