Sub topic 10
Finding the Wasted Work
This chapter assumes you can read nested loops and recursion in Python, know what a dictionary does, and can state a loop's cost in Big-O. It also assumes you have a correct brute-force solution. You will learn how to read that solution for work it does more than once or does for no reason. Each piece of wasted work you find points toward a faster algorithm.
The core question
A brute-force solution is slow because it enumerates the whole search space and does the full check on every candidate. Not all of that effort is needed. To find the waste, ask one question about the innermost loop: "What does this step compute, and has it computed it before?"
If the answer is "yes, a moment ago, for a neighboring candidate," you have found redundant work.
A worked example: sliding window sums
Suppose you need the sum of every block of k consecutive elements. The brute force restarts the sum for every window. The code below counts additions so you can see the cost.
def window_sums_brute(nums, k):
additions = 0
sums = []
for start in range(len(nums) - k + 1):
total = 0
for i in range(start, start + k):
total += nums[i]
additions += 1
sums.append(total)
return sums, additions
print(window_sums_brute([3, 1, 4, 1, 5, 9, 2, 6], 4))
# ([9, 11, 19, 17, 22], 20)Look at windows starting at 0 and 1. The first sums 3, 1, 4, 1. The second sums 1, 4, 1, 5. Three of those four additions are repeats. Neighboring windows overlap in k - 1 elements, so the brute force does about (n - k + 1) * k additions when about n would do.
Once you have named the waste, the fix follows from it. Keep the previous total, add the element that enters the window, and subtract the one that leaves.
def window_sums_reuse(nums, k):
ops = 0
if k > len(nums):
return [], ops
total = sum(nums[:k])
ops += k
sums = [total]
for start in range(1, len(nums) - k + 1):
total += nums[start + k - 1] - nums[start - 1]
ops += 1
sums.append(total)
return sums, ops
print(window_sums_reuse([3, 1, 4, 1, 5, 9, 2, 6], 4))
# ([9, 11, 19, 17, 22], 8)The cost drops from O(n·k) to O(n). The faster version came from reading the brute force closely. It was not a new idea brought in from elsewhere.
Four kinds of waste
Most redundant work in brute-force code falls into one of these categories.
| Kind of waste | What it looks like | Typical signal |
|---|---|---|
| Recomputed aggregate | A sum, max, or count rebuilt from scratch for overlapping ranges | Inner loop range shifts by one each outer step |
| Repeated lookup | The same "is value X present?" scan done for many candidates | Inner loop searches for something that depends only on the outer variable |
| Overlapping subproblems | Recursion calls the same arguments many times | Recursion tree has identical subtrees |
| Hopeless candidates | Full checks on candidates that earlier facts already rule out | You could reject the candidate before finishing the check |
The fix for each kind is covered in the next chapter. Your job here is diagnosis.
Common mistakes
- Optimizing the outer loop. The innermost step runs most often, so that is where the waste piles up. Start there.
- Removing work that is not redundant. Skipping a candidate is only safe if you can say why it cannot be the answer. Run your stress test after every change.
- Guessing instead of counting. A counter like
additionsabove shows you where the time goes. Plain intuition can mislead you.
Exercise
In the two-sum brute force, the inner loop over j checks whether nums[i] + nums[j] == target. Describe the inner loop's question as a sentence, say which kind of waste it is, and explain why.
Show answer
The question is "does any element after position i equal target - nums[i]?" This is a repeated lookup. Every outer step scans the array again for a value that depends only on i, and the scans cover elements already visited. Remembering the values seen so far would answer each question without a scan.
Exercise
A recursive fib(n) returns fib(n-1) + fib(n-2). For fib(5), how many times is fib(2) called, and which kind of waste is this?
Show answer
fib(2) is called 3 times. This is overlapping subproblems: identical calls appear in separate branches of the recursion tree, so caching each result would remove the repeats.