Sub topic 3
Using Brute Force to Test Faster Code
This chapter assumes you already have a working brute-force solution. It also assumes you can read Python dictionaries and recursion and know introductory Big-O notation.
Stress Testing Against a Brute-Force Oracle
A brute-force solution is slow, but you can trust it. That makes it useful as an oracle, meaning a reference answer you compare against. In a stress test, you generate many small random inputs, run both versions on each one, and stop at the first input where they disagree.
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 stress_test(trials=1000):
for _ in range(trials):
nums = [random.randint(-5, 5) for _ in range(random.randint(0, 8))]
target = random.randint(-10, 10)
a = two_sum_brute(nums, target)
b = two_sum_fast(nums, target)
assert (a is None) == (b is None), (nums, target, a, b)
if b is not None:
i, j = b
assert i != j and nums[i] + nums[j] == target, (nums, target, b)
print("all tests passed")
stress_test()Finding the Wasted Work
For each j, the brute force scans every earlier i again, looking for the value target - nums[j]. That repeated scan is the waste. The question to ask is: "What am I recomputing that I could remember?"
From Brute Force to an Efficient Algorithm
Once you can name the wasted work, a standard tool usually removes it:
| Wasted work | Fix |
|---|---|
| Repeated lookups | Hashing (dict or set) |
| Searching unordered data | Sorting, then two pointers or binary search |
| Recomputing range sums | Precomputed prefix sums |
| Re-solving the same subproblem | Memoization |
Cutting the Search Short: Pruning and Backtracking
Sometimes you can't remove the search, but you can skip parts of it. Backtracking builds a candidate one choice at a time. Pruning abandons a branch as soon as it can't lead to a valid answer. In subset sum with non-negative items, a branch whose remaining target drops below zero can never recover, so you stop searching it. The answer stays correct, because only branches that cannot succeed are skipped.
Explaining Your Approach in Reviews and Interviews
Describe the work in this order: the search space, the brute-force cost, the waste you found, the fix, and the new cost. For example: "Checking all pairs is O(n²). The inner loop repeats a lookup, so a dictionary brings it to O(n). I checked it against the brute force on random inputs."
Exercise
A fast solution passes 1,000 stress-test trials on arrays of length 0 to 8 with values from -5 to 5. Name one kind of bug these tests could miss.
Show answer
Bugs that only show up on large inputs or large values, such as integer overflow in other languages, deep-recursion limits, or timeouts. Small random tests check logic, not scale, so add separate tests at the maximum input size.