Sub topic 11
From Brute Force to an Efficient Algorithm
This chapter assumes you can write Python functions and recursion, use lists and dictionaries, and read Big-O notation. It also assumes you have a working brute-force solution and have already found where it repeats work, as covered in the previous chapter. Here you turn that diagnosis into a faster algorithm using one of four techniques: hashing, sorting, precomputation, and memoization.
The Working Model: Replace a Repeated Question with a Cheap Answer
Every brute-force solution keeps asking a question inside its loops. "Is there an earlier element equal to target - x?" "What is the sum of nums[l:r]?" "Can the remaining items reach this total?" The brute force answers that question from scratch every time. Each optimization in this chapter answers it faster, either by storing earlier answers or by arranging the data so the answer is cheap to compute.
The table below maps the symptom you see in the brute force to the technique that usually removes it.
| Symptom in the brute force | Technique | Typical gain |
|---|---|---|
| Inner loop searches earlier elements for a specific value | Hashing (set or dict lookup) | O(n²) to O(n) expected |
| Inner loop searches for a value that is "too big" or "too small" | Sorting, then two pointers or binary search | O(n²) to O(n log n) |
| The same range, prefix, or aggregate is recomputed per query | Precomputation (prefix sums, tables) | O(n·q) to O(n + q) |
| Recursion reaches the same arguments by different paths | Memoization | Exponential to (number of distinct states) × (work per state) |
Hashing: Remember What You Have Seen
The brute-force two-sum checks every pair. For each j, its inner loop asks: "is there an i < j with nums[i] == target - nums[j]?" A dictionary answers that in expected O(1) time.
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
print(two_sum_fast([3, 3], 6)) # (0, 1)
print(two_sum_fast([3, 1, 4], 6)) # None: 3 must not pair with itselfThe order of the two statements inside the loop matters. Checking before inserting means seen holds only indices strictly less than j. That is the same invariant the brute force enforced with range(i + 1, len(nums)). If you insert first, [3, 1, 4] with target 6 wrongly pairs index 0 with itself.
Common mistakes with hashing:
- Building the whole dictionary before the loop. Duplicates overwrite earlier indices, and you have to add an explicit
i != jcheck. - Forgetting that O(1) is the expected cost. Adversarial keys can degrade a hash table, which matters for services that accept untrusted input. For contest and interview problems, the expected bound is the accepted answer.
- Hashing unhashable values. In Python, convert lists to tuples before using them as keys.
Sorting: Make the Data Answer Order Questions
Sorting helps when the repeated question involves order, such as "is this sum too big or too small?" After sorting, two pointers can walk inward from both ends. If the sum is too small, only moving the left pointer can increase it. If it is too big, only moving the right pointer can decrease it. Each step rules out a whole row or column of pairs that the brute force would have checked one by one.
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:
a, b = order[lo], order[hi]
return (min(a, b), max(a, b))
if s < target:
lo += 1
else:
hi -= 1
return None
print(two_sum_sorted([10, 2, 7, 5], 12)) # (0, 1)The main trap is losing the original indices. Sorting nums directly gives you positions in the sorted list, which do not answer the original question. Sorting the index list order by value keeps the mapping back to the input.
Sorting costs O(n log n), so for two-sum it is slower than hashing. It wins in two situations. The first is when you need ordered structure anyway, as in three-sum, closest-pair-sum, or interval problems. The second is when memory is tight, because sorting in place needs no extra table.
Precomputation: Pay Once, Answer Many Times
Suppose you must answer q queries, each asking for the sum of a half-open range nums[l:r]. The brute force sums each range separately, costing O(n) per query. Every query rescans elements that earlier queries already added. A prefix-sum array stores prefix[k] = sum(nums[:k]), so every range sum becomes one subtraction.
def range_sums_brute(nums, queries):
return [sum(nums[l:r]) for l, r in queries]
def range_sums_prefix(nums, queries):
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
return [prefix[r] - prefix[l] for l, r in queries]
nums = [4, -1, 2, 7]
queries = [(0, 4), (1, 3), (2, 2)]
print(range_sums_brute(nums, queries)) # [12, 1, 0]
print(range_sums_prefix(nums, queries)) # [12, 1, 0]The total cost drops from O(n·q) to O(n + q). The leading 0 in prefix is what makes the empty range and the range starting at index 0 work without special cases. Leaving it out is the most common off-by-one error with this technique.
The same idea extends to 2D prefix sums for rectangle queries, sieves for primality, and lookup tables of factorials. The pattern is always the same: if the answers depend only on the input and not on the query order, compute them once up front.
Memoization: Never Solve the Same Subproblem Twice
Recursive brute force often reaches the same state by different paths. In subset sum, skipping item 0 and taking item 1 can leave the same remaining as taking item 0 and skipping item 1. The state of the search is the pair (i, remaining). If two paths reach the same state, the rest of the search is identical, so you can cache it.
from functools import lru_cache
def subset_sum_memo(items, target):
items = tuple(items)
@lru_cache(maxsize=None)
def can(i, remaining):
if remaining == 0:
return True
if i == len(items):
return False
return can(i + 1, remaining - items[i]) or can(i + 1, remaining)
return can(0, target)
print(subset_sum_memo([3, 34, 4, 12, 5, 2], 9)) # True (4 + 5)
print(subset_sum_memo([3, 34, 4, 12, 5, 2], 30)) # FalseThe running time is bounded by the number of distinct states times the work per state. For non-negative integers, remaining only takes values from 0 to target, so this is O(n · target) instead of O(2ⁿ). That bound is pseudo-polynomial: it is fast when target is small and slow when target is a 60-bit number. In the large-target case the bitmask brute force, or a meet-in-the-middle split, can actually be the better choice.
Common mistakes with memoization:
- An incomplete cache key. If the result depends on something that is not in the arguments, such as a mutable list modified during the search, the cache returns wrong answers. Every input that affects the result must be part of the key, or must be fixed for the life of the cache.
- Unhashable arguments.
lru_cacheneeds hashable arguments, which is whyitemsis converted to a tuple and captured by the closure instead of being passed in. - Recursion depth. Python's default limit is about 1000 frames. For large
n, either raise the limit withsys.setrecursionlimitor convert the recursion into a bottom-up table, which is dynamic programming. - Few repeated states. Memoization speeds things up only when states actually repeat. A permutation search whose state includes the full ordering so far never repeats, so the cache just uses memory. The fix there is to choose a smaller state. For the traveling salesman,
(visited set, current city)gives the O(2ⁿ · n²) Held–Karp algorithm.
Keep the Brute Force as the Referee
Every technique above changes the code in ways that cause subtle bugs: insertion order, lost indices, off-by-one prefixes, incomplete cache keys. Do not delete the brute force. Run it against the new version on small random inputs, as shown in the stress-testing chapter. This check assumes the range-sum functions above are in the same file:
import random
def check_prefix(trials=500):
for _ in range(trials):
nums = [random.randint(-9, 9) for _ in range(random.randint(0, 10))]
n = len(nums)
queries = []
for _ in range(5):
l = random.randint(0, n)
r = random.randint(l, n)
queries.append((l, r))
assert range_sums_brute(nums, queries) == range_sums_prefix(nums, queries), (nums, queries)
print("prefix sums agree")
check_prefix()Include empty inputs and empty ranges in the generator. Those cases are where these optimizations most often break.
Choosing Among Techniques
When more than one technique applies, compare them on these criteria:
- Time bound against the limits. Check the bound against the input sizes using the estimation method from the earlier chapter. Do not pick O(n log n) when O(n) is just as simple.
- Memory. Hashing and memoization trade memory for time. A memo table with 10⁸ states will not fit in memory, even if the time bound looks fine.
- What the output needs. Two pointers on sorted data naturally finds every pair or the closest pair. A single dictionary pass finds the first match.
- Simplicity and risk. The smallest change that removes the repeated work is easier to review and to stress test.
Exercise
Write a function count_pairs(nums, target) that returns how many index pairs i < j satisfy nums[i] + nums[j] == target, in O(n) expected time. Which line of the two-sum hashing solution must change, and why?
Show answer
Store counts instead of indices: from collections import Counter, then seen = Counter(); total = 0; for x in nums: total += seen[target - x]; seen[x] += 1; return total. Instead of returning on the first match, add the number of earlier elements equal to target - x. Keep the check-before-insert order so each pair is counted once with i < j and no element pairs with itself.
Exercise
A colleague memoizes a recursive search with @lru_cache on can(i, remaining), but inside the function they also append chosen items to a global list path and return False whenever len(path) > k. Why can the cached results be wrong, and how do you fix it?
Show answer
The result depends on len(path), which is not part of the cache key. The same (i, remaining) reached with different path lengths shares one cached answer. Make the count part of the state, for example can(i, remaining, used), and drop the global list, or rebuild the path afterwards from the memoized decisions.
Exercise
You need the sum of nums[l:r] for 10^5 queries on an array of 10^5 elements that never changes. Estimate the operation counts of the brute force and of prefix sums, and state which one you would ship.
Show answer
The brute force does up to about 10^5 × 10^5 = 10^10 additions, which is far too slow. Prefix sums take about 10^5 operations to build plus 10^5 subtractions, around 2 × 10^5 in total. Ship prefix sums, and keep the brute force for stress tests.