Sub topic 10
Finding the Wasted Work
A working brute-force solution tells you exactly what work the computer does. To make it faster, read that work closely and find the parts that repeat, recompute, or could never matter. This chapter teaches how to diagnose that waste. The next chapter covers the standard fixes in full, so the fixes here appear only far enough to show that the diagnosis was right.
This chapter assumes you can write Python loops and recursive functions, use lists and dictionaries, and read Big-O notation. It also assumes you have seen the brute-force two-sum solution and the idea of a search space from earlier chapters.
Waste Is Specific, Not Vague
Saying "this is O(n²), so it's slow" names a cost. It doesn't explain why the code is slow. Waste is a concrete statement of the form "this loop computes X, and X was already known" or "this loop checks candidates that cannot be the answer." You can act on a statement like that. You can't act on a bare complexity bound.
Most redundant work in brute-force code falls into a few patterns:
| Waste pattern | Symptom in the code | Typical direction of the fix |
|---|---|---|
| Repeated search | Inner loop scans a collection looking for one value | Hash map or sorted structure for lookup |
| Recomputed aggregate | Sum, max, or count recomputed over a range that grew by one element | Running total or prefix array |
| Loop-invariant work | Expression inside a loop doesn't use that loop's variable | Hoist it out of the loop |
| Overlapping subproblems | Recursive function called many times with the same arguments | Memoization or a bottom-up table |
| Symmetric duplicates | Candidates (a, b) and (b, a), or rotations of a tour, both evaluated | Enumerate one canonical form |
| Hopeless candidates | Branches explored after they can no longer succeed | Pruning (covered in a later chapter) |
A Diagnostic Procedure
Waste rarely jumps out on a first read. A fixed set of questions finds it more reliably than staring at the code.
Code can contain more than one pattern. Keep going after the first "yes".
Step 1: Measure Before You Theorize
Instrument the brute force with a counter. The number grounds the discussion and lets you confirm later that a change actually removed work.
def two_sum_brute_counted(nums, target):
checks = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
checks += 1
if nums[i] + nums[j] == target:
return (i, j), checks
return None, checks
print(two_sum_brute_counted(list(range(1000)), -1))This prints (None, 499500). With no valid pair, every one of the n(n−1)/2 pairs is checked. Test the worst case on purpose. If the answer happens to sit early in the input, the counter will make the code look fast when it isn't.
Step 2: Name the Question Each Inner Loop Answers
This is the most productive habit in the chapter. For each inner loop, write one sentence that describes what it computes for a fixed value of the outer variable.
In two-sum, the brute force fixes i and scans forward. Turn the loops around so the outer loop fixes the later index, and the question becomes clearer:
def two_sum_reframed(nums, target):
for j in range(len(nums)):
need = target - nums[j]
# Question this loop answers: does `need` occur in nums[:j]?
for i in range(j):
if nums[i] == need:
return (i, j)
return None
print(two_sum_reframed([3, 8, 4, 5], 9)) # (2, 3)The search space hasn't changed. It is still every unordered pair, and the function still finds a valid pair exactly when one exists, though it may return a different one than the original brute force does. The sentence in the comment now names the waste. Each iteration asks a membership question about nums[:j], and that prefix is one element longer than last time. The loop rescans j−1 elements it has already seen. The repeated-search pattern says to remember those elements in a structure that answers "is this value present?" in O(1). That structure is the dictionary in the fast two-sum solution.
The reframing step matters. Many people jump straight from the brute force to the hash map and can't explain why the map works. If you state the inner loop's question first, the data structure follows from it.
Step 3: Find Aggregates Recomputed from Scratch
The maximum-subarray-sum problem asks for the largest sum of a contiguous, non-empty slice. Its brute force enumerates every (i, j) and sums the slice:
import random
def max_subarray_cubic(a):
best = a[0]
for i in range(len(a)):
for j in range(i, len(a)):
best = max(best, sum(a[i:j + 1]))
return best
def max_subarray_quadratic(a):
best = a[0]
for i in range(len(a)):
running = 0
for j in range(i, len(a)):
running += a[j] # sum(a[i:j+1]) built incrementally
best = max(best, running)
return best
for _ in range(2000):
a = [random.randint(-10, 10) for _ in range(random.randint(1, 12))]
assert max_subarray_cubic(a) == max_subarray_quadratic(a), a
print("versions agree")The sum(a[i:j + 1]) call hides a third loop, so the cubic version runs in O(n³). The waste is easy to see once you write out consecutive iterations. sum(a[i:j+1]) equals sum(a[i:j]) + a[j], and the code just computed sum(a[i:j]) on the previous step. Carrying a running total removes a whole loop. The random comparison at the end checks the change the same way the stress-testing chapter does.
The quadratic version still has waste. Different values of i recompute overlapping running sums, and with prefix sums or Kadane's algorithm the problem drops to O(n). Removing one layer of waste often exposes the next one.
Step 4: Look for Loop-Invariant Work
An expression is loop-invariant if its value doesn't depend on the loop's variable. Recomputing it on every iteration is pure waste:
def count_close_pairs(values, percent):
count = 0
for i in range(len(values)):
for j in range(i + 1, len(values)):
threshold = max(values) * percent / 100 # depends on neither i nor j
if abs(values[i] - values[j]) <= threshold:
count += 1
return count
def count_close_pairs_hoisted(values, percent):
threshold = max(values) * percent / 100
count = 0
for i in range(len(values)):
for j in range(i + 1, len(values)):
if abs(values[i] - values[j]) <= threshold:
count += 1
return count
data = [10, 12, 30, 31, 50]
print(count_close_pairs(data, 5), count_close_pairs_hoisted(data, 5)) # 2 2Because max(values) hides a loop, the first version is O(n³). Hoisting the threshold out of the loops makes it O(n²). To find this pattern, go through each expression and list the loop variables it reads. If it reads none of the variables of its innermost enclosing loop, move it outward.
Step 5: Log Arguments in Recursive Searches
Recursive brute force can hide redundant work that no loop structure shows. Count calls per distinct argument:
from collections import Counter
calls = Counter()
def paths(r, c):
"""Number of monotone lattice paths from (r, c) to (0, 0)."""
calls[(r, c)] += 1
if r == 0 or c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
print(paths(10, 10))
print(sum(calls.values()), "calls for", len(calls), "distinct inputs")
print(calls.most_common(3))This prints 184756, then 369511 calls for 120 distinct inputs. The function makes over three thousand times more calls than it has distinct subproblems. calls.most_common shows that base-case cells near the edges are hit tens of thousands of times. A large ratio of total calls to distinct arguments means overlapping subproblems, and caching results by argument removes that waste. A ratio near 1 means memoization won't help, and you should look elsewhere.
Step 6: Check for Symmetric and Hopeless Candidates
Some waste lies in the search space itself, not in how each candidate is evaluated.
- Symmetric duplicates. Two-sum uses
j in range(i + 1, n)so that it never tests both (i, j) and (j, i). The traveling-salesman brute force fixes city 0 so that rotations of the same tour aren't counted. Each tour is still evaluated twice, once in each direction, so for a symmetric distance matrix you could keep only orderings where the second city is less than the last one and halve the work. Symmetry fixes usually save a constant factor or a factorial factor. They rarely change the shape of the growth. - Hopeless candidates. In subset sum with non-negative items, any partial subset whose total already exceeds the target can't be extended into a solution. Every completion of that subset is wasted work. Cutting those branches is called pruning, and a later chapter covers it.
Confirm That the Waste Was Real
Every diagnosis is a hypothesis until you check it. After each change:
- Rerun the instrumented counter on the worst-case input and confirm that the count dropped by the amount you predicted.
- Compare the new version against the original brute force on many small random inputs.
- Record the new complexity and check it against the input limits, as in the cost-estimation chapter.
If the count didn't drop as predicted, your model of where the time goes was wrong. Go back to Step 1.
Exercise
A brute force for "count pairs i < j with nums[i] == nums[j]" uses two nested loops and compares every pair. State the question the inner loop answers for a fixed j (with i ranging over 0..j-1), name the waste pattern, and describe what information you would need to carry from one j to the next.
Show answer
For a fixed j, the inner loop answers "how many earlier elements equal nums[j]?" This is the repeated-search pattern: each j rescans a prefix that grew by one element. You need a running count of how many times each value has appeared so far, for example a dictionary from value to count. Add count[nums[j]] to the answer, then increment it. Total time becomes O(n) expected.
Exercise
A recursive function best(i, cap) solves a knapsack problem. You instrument it on an input with 20 items and cap 50 and see 1,048,575 calls but only 900 distinct (i, cap) pairs. What does this tell you, and what condition must hold before you cache results?
Show answer
The ratio of about 1,165 calls per distinct argument shows heavy overlapping subproblems, so caching by (i, cap) would cut the work to roughly 900 evaluations. This is safe only if the result depends on nothing except i and cap, meaning the function reads no mutable shared state, such as a list of chosen items, that changes between calls.
Exercise
In maxsubarrayquadratic, which expression would you inspect next to find remaining waste, and what is redundant about it?
Show answer
Inspect the running sums across different values of i. The sum for a slice starting at i+1 equals the sum for the slice starting at i minus a[i], so the inner loop for each new i recomputes totals that were already available. Prefix sums, or tracking the best sum ending at each position as Kadane's algorithm does, remove this and give O(n).