Sub topic 9
Using Brute Force to Test Faster Code
A brute-force solution is slow, but you can trust it. An optimized solution is fast, but its correctness is harder to see. Stress testing combines the two. You run both on thousands of small random inputs and compare their answers. Any disagreement points to a concrete input where at least one of them is wrong, and it is almost always the fast one.
This chapter assumes you can write Python functions and loops, know what a dictionary does, and have read the earlier chapters on brute-force enumeration and correctness. The examples use the two-sum and subset-sum solutions from those chapters.
Why Hand-Written Tests Are Not Enough
When you write test cases by hand, you test the cases you thought of. Bugs in optimized code tend to live in the cases you did not think of: duplicate values, a value that pairs with itself, an empty input, negative numbers, or an off-by-one at a boundary. These inputs are usually tiny. A random generator that produces thousands of tiny inputs will reach them quickly, and you don't need to predict which ones matter.
You still need something to tell you the right answer for each random input. That is the job of the oracle.
What a Test Oracle Is
A test oracle is any procedure that decides whether an output is correct for a given input. A brute-force solution works well as an oracle for three reasons:
- It is short and direct, so you can check it by reading it.
- It shares no clever logic with the fast solution, so the two are unlikely to have the same bug.
- On small inputs its slowness does not matter.
A stress test has four parts: a random input generator, the oracle, the code under test, and a comparator that decides whether the two outputs agree.
Building a Stress-Test Harness
The script below is complete and runnable. It includes both two-sum solutions, a comparator, a generator, and the test loop.
import random
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
def two_sum_fast(nums, target):
seen = {}
for j, x in enumerate(nums):
if target - x in seen:
return (seen[target - x], j)
seen[x] = j
return None
def check(nums, target, expected, got):
"""Return an error message, or None if `got` is acceptable."""
if (expected is None) != (got is None):
return f"existence mismatch: brute={expected}, fast={got}"
if got is not None:
i, j = got
if not (0 <= i < len(nums) and 0 <= j < len(nums)):
return f"index out of range: {got}"
if i == j:
return f"same index used twice: {got}"
if nums[i] + nums[j] != target:
return f"pair does not sum to target: {got}"
return None
def random_case(rng):
n = rng.randint(0, 8)
nums = [rng.randint(-5, 5) for _ in range(n)]
target = rng.randint(-10, 10)
return nums, target
def stress_test(fast, trials=10_000, seed=0):
rng = random.Random(seed)
for t in range(trials):
nums, target = random_case(rng)
expected = two_sum_brute(nums, target)
got = fast(nums, target)
error = check(nums, target, expected, got)
if error:
print(f"trial {t}: nums={nums}, target={target}")
print(f" {error}")
return False
print(f"all {trials} tests passed")
return True
if __name__ == "__main__":
stress_test(two_sum_fast)Running it prints all 10000 tests passed. Several design choices in this harness are deliberate, and the next sections explain them.
The comparator checks validity, not equality
Two-sum can have several correct answers. On nums = [1, 2, 3, 4] with target = 5, the brute force returns (0, 3) because its outer loop fixes the smallest first index. The fast version returns (1, 2) because it stops at the smallest second index. Both answers are correct. A comparator that tested expected == got would report a failure that is not real.
The comparator therefore uses the oracle only for the question that has a single answer: does a valid pair exist? It then checks the fast output directly against the problem statement: indices in range, distinct, and summing to the target.
| Problem shape | Comparator strategy | Example |
|---|---|---|
| Single correct answer | Exact equality | Minimum tour cost, count of subsets |
| Many correct answers | Oracle decides existence or optimal value; validate the fast output's properties | Two-sum indices, any shortest path |
| Floating-point result | Equality within a tolerance, such as `math.isclose` | Geometric distances |
| Order-insensitive collection | Compare sorted outputs or sets | "Return all pairs" in any order |
Small inputs and narrow value ranges
The generator uses lists of at most 8 numbers between -5 and 5. That range is narrow on purpose. With only 11 possible values, duplicates and self-pairs (a value equal to half the target) come up all the time. If values ranged up to a million, almost no random pair would hit the target, and most trials would test only the "no answer" path.
Small sizes also keep the oracle fast and make failures easy to read. Testing on large inputs is a separate job from testing correctness; use a different test for speed.
Seeded randomness
The harness creates its own random.Random(seed) instead of using the global generator. A fixed seed makes every run produce the same sequence of inputs, so a failure you saw once will happen again when you rerun. After you fix the bug, try several other seeds to cover new inputs.
Watching It Catch a Bug
Here is a plausible-looking mistake: storing the current value in the dictionary before looking up its complement. Append this to the script above and run it.
def two_sum_buggy(nums, target):
seen = {}
for j, x in enumerate(nums):
seen[x] = j # bug: stored before the lookup
if target - x in seen:
return (seen[target - x], j)
return None
stress_test(two_sum_buggy)When x is exactly half the target, the lookup finds the element just stored and returns a pair like (j, j). The harness stops at the first such trial and reports either same index used twice (when a valid pair also existed) or existence mismatch (when no valid pair existed). The exact trial number depends on the seed, but the bug shows up within the first few dozen trials.
A hand-written test suite using inputs like [2, 7, 11, 15] with target 9 would pass this buggy function.
Shrinking the Failing Input
The first failing input may be bigger than it needs to be. A smaller failing input makes the cause easier to see. One simple way to get one is to try sizes in increasing order and return the first failure found:
def find_smallest_failure(fast, max_n=8, trials_per_size=2000, seed=0):
rng = random.Random(seed)
for n in range(max_n + 1):
for _ in range(trials_per_size):
nums = [rng.randint(-3, 3) for _ in range(n)]
target = rng.randint(-6, 6)
expected = two_sum_brute(nums, target)
error = check(nums, target, expected, fast(nums, target))
if error:
return nums, target, error
return None
print(find_smallest_failure(two_sum_buggy))For the buggy version this returns a one-element list, such as ([-1], -2, 'existence mismatch: brute=None, fast=(0, 0)'). A single element that pairs with itself points straight at the bug. Property-based testing libraries such as Hypothesis shrink failing inputs automatically, and they are worth adopting once the habit is established. The hand-rolled loop is enough to start.
The Generator Encodes the Input Contract
The backtracking subset-sum solution from an earlier chapter assumes all items are non-negative. Its pruning rule, "stop when the remaining sum goes below zero," is only valid under that assumption. A stress test makes the assumption visible:
import random
def subset_sum_exists(items, target):
n = len(items)
for mask in range(1 << n):
total = sum(items[i] for i in range(n) if (mask >> i) & 1)
if total == target:
return True
return False
def subset_sum_backtrack(items, target):
# Assumes all items are non-negative, so a negative remainder can never recover.
items = sorted(items, reverse=True)
def search(i, remaining):
if remaining == 0:
return True
if remaining < 0 or i == len(items):
return False
return search(i + 1, remaining - items[i]) or search(i + 1, remaining)
return search(0, target)
def stress_subset(allow_negative, trials=5000, seed=1):
rng = random.Random(seed)
low = -5 if allow_negative else 0
for _ in range(trials):
items = [rng.randint(low, 9) for _ in range(rng.randint(0, 10))]
target = rng.randint(0, 30)
if subset_sum_exists(items, target) != subset_sum_backtrack(items, target):
return items, target
return None
print(stress_subset(allow_negative=False))
print(stress_subset(allow_negative=True))The first call prints None. The second almost certainly prints a counterexample. The smallest kind is items = [5, -3] with target = 2. Taking 5 leaves a remainder of -3, so the search prunes that branch, even though adding -3 next would reach the target exactly.
When a disagreement appears, decide which side is wrong: the code or the generator. If negative items are outside the problem's stated input range, restrict the generator. If they are allowed, the pruning rule is a real bug. Either way, the stress test has made you write the contract down.
Common Failure Modes of Stress Tests
- The generator misses the hard cases. If it never produces empty lists, duplicates, or negative values, the test never exercises them. List the edge cases from the correctness chapter and confirm the generator can produce each one.
- The comparator is too strict. Equality checks on problems with several valid answers, or on floating-point results, report failures that are not bugs. Developers who see enough of these start ignoring failures.
- The comparator is too loose. Checking only that the fast output is not
Nonemisses wrong pairs. Validate every property the problem requires. - Inputs are too large for the oracle. An O(2^n) or O(n!) oracle on n = 25 will stall the test. Size the generator to the oracle's cost, as estimated in the complexity chapter.
- Unseeded randomness. A failure you cannot reproduce costs more time than it saves.
- Nondeterministic code under test. If the fast solution depends on set iteration order or timing, failures may come and go between runs. Make the comparator order-insensitive where order does not matter.
Where Stress Testing Fits in Your Workflow
Write the brute force first, test it by hand on a few examples, and keep it. When you write the optimized version, run the stress test before any large-input timing tests. After each change to the fast code, rerun it. In a codebase, the brute force and the harness can go into the test suite as a regular test with a fixed seed and a modest trial count, so later refactors are checked against the same reference.
Exercise
A function max_pair_sum_fast(nums) returns the largest value of nums[i] + nums[j] for i < j, or None if the list has fewer than two elements. Write a brute-force oracle and a comparator for it. Should the comparator use exact equality or a property check, and why?
Show answer
The oracle loops over all i < j with nested loops, tracks the maximum of nums[i] + nums[j], and returns None if no pair exists. Exact equality is correct here. The problem asks for a value, not for indices, so there is exactly one correct answer for each input. Different index pairs can reach the same maximum, but the returned number is the same either way.
Exercise
A teammate's stress test for two-sum generates lists of length 0 to 8 with values from -1,000,000 to 1,000,000 and random targets in the same range. It passes 100,000 trials, but the buggy version from this chapter also passes. Explain why and fix the generator.
Show answer
With values spread over two million possibilities, a random target almost never equals the sum of two list elements, and almost never equals twice a single element. Nearly every trial tests only the "no pair exists" case, where the buggy and correct versions both return None. Narrow the ranges, for example values in -5..5 and targets in -10..10, so that duplicates, self-pairs, and matching pairs occur often.
Exercise
Your stress test reports that a fast solution and its brute-force oracle disagree on an input. List the steps you take before changing the fast solution.
Show answer
First, shrink the input to the smallest case that still fails. Second, work out the correct answer by hand for that case to confirm which side is wrong, because the oracle could be buggy. Third, check whether the input is within the problem's stated constraints. If it is not, the generator needs fixing, not the code. Only then fix the fast solution, rerun the stress test with the same seed to confirm the fix, and run it again with a few new seeds.