Sub topic 11
From Brute Force to an Efficient Algorithm
This chapter assumes you already have a working brute-force solution, a stress test that compares it against new code, and a sense of where that solution repeats work. The previous chapter covered how to find the wasted work. This chapter matches each common kind of waste to a standard fix.
Match the Waste to the Technique
Most optimizations replace a repeated computation with a stored one. The useful question is what the brute force keeps recomputing.
| Repeated work in the brute force | Technique | Typical gain |
|---|---|---|
| Scanning for a matching value | Hashing | O(n) scan becomes expected O(1) lookup |
| Comparing every pair to find an order or a match | Sorting, then a sweep | O(n²) becomes O(n log n) |
| Summing or counting the same range many times | Precomputation (prefix arrays) | O(n) per query becomes O(1) |
| Solving the same subproblem on several branches | Memoization | Exponential becomes polynomial in the number of distinct states |
Hashing: Remember What You Have Seen
In brute-force two-sum, the inner loop searches for target - nums[i]. A dictionary of the values seen so far answers that question in one step:
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 NoneThe lookup happens before the insert, so an element is never paired with itself.
Sorting: Let Order Do the Searching
If you can't hash the values, or you need the result in order, sort first. On sorted data, two pointers can find a pair that sums to target with one sweep from both ends.
def two_sum_sorted(nums, target):
order = sorted(range(len(nums)), key=lambda k: nums[k])
lo, hi = 0, len(order) - 1
while lo < hi:
s = nums[order[lo]] + nums[order[hi]]
if s == target:
return tuple(sorted((order[lo], order[hi])))
if s < target:
lo += 1
else:
hi -= 1
return NoneSorting indices instead of values keeps the original positions available. Programmers often sort the values directly and then return indices that no longer match the input.
Precomputation: Pay Once, Answer Many Times
Answering many "sum of a[l..r]" queries by looping costs O(n) per query. A prefix array costs O(n) to build, then answers each query in O(1):
def build_prefix(a):
prefix = [0]
for x in a:
prefix.append(prefix[-1] + x)
return prefix
def range_sum(prefix, l, r):
# inclusive l..r, 0-indexed
return prefix[r + 1] - prefix[l]
p = build_prefix([3, 1, 4, 1, 5])
print(range_sum(p, 1, 3)) # 6The extra leading zero removes the special case for l == 0. Without it, you get off-by-one errors.
Memoization: Cache Repeated Subproblems
The recursive subset-sum search calls search(i, remaining) for the same pair of arguments along different branches. Caching those results bounds the work by the number of distinct states, len(items) × (target + 1):
from functools import lru_cache
def subset_sum_memo(items, target):
# Assumes non-negative integers.
items = tuple(items)
@lru_cache(maxsize=None)
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)
print(subset_sum_memo([3, 34, 4, 12, 5, 2], 9)) # TrueKeep the Oracle in the Loop
Every change above can introduce a bug that the brute force can't have. After each optimization, run the randomized stress test from the earlier chapter. Compare outputs when there is exactly one correct answer, and check validity when the two versions may pick different valid answers.
Exercise
You must answer 100,000 queries, each asking how many even numbers are in a[l..r], for an array of 100,000 integers. The brute force loops over the range for each query. Which technique applies, and what are the new time costs?
Show answer
Precomputation. Build a prefix count where prefix[k] is the number of even values among the first k elements, in O(n). Each query is then prefix[r+1] - prefix[l], which is O(1). The total is O(n + q), about 200,000 operations, compared with up to 10^10 for the brute force.
Exercise
A memoized function takes (i, remaining) with 0 ≤ i ≤ 50 and 0 ≤ remaining ≤ 10^9. Why might memoization fail to help here?
Show answer
There can be up to 51 × (10^9 + 1) distinct states. Memoization bounds the work by the number of distinct states actually reached, so if the branches rarely share states, the cache saves little time and uses a lot of memory. Pruning or a different formulation, such as meet-in-the-middle, may be a better fit.