How to optimize a brute force solution
How to optimize a brute force solution: audit its loops for repeated and discarded work, then fix each kind with the matching tool. A worked example takes a 1.3 trillion operation scan down to 20,000 steps.
How to optimize a brute force solution comes down to one move: find the work it repeats or throws away, then replace that work with something you remember, sort, or index. Brute force is slow because it asks the same question many times; the fix is usually a data structure or ordering that answers each question once.
What does it mean to optimize a brute force solution?
It means keeping the answer exactly the same while shrinking the amount of work needed to produce it. You are not hunting for a clever trick; you are removing redundancy from something that already works.
That framing matters because most people get stuck at the wrong moment. They write a correct triple loop, feel the inefficiency, and then try to recall a pattern by name: is this a sliding window, is this a heap, is this DP? Guessing the pattern from the problem title is a lottery. Reading your own brute force is not. The brute force has already told you what the problem is asking, because every line of it is a literal translation of the statement. What it has not told you is where it is being wasteful, and that is a question you can answer by inspection.
A correct brute force is also worth more than it looks. It is a reference implementation. Once you have a faster version, you can generate a thousand small random inputs, run both, and compare outputs. Every optimization is a refactor that can silently change behaviour, and the slow version is the cheapest oracle you will ever get. I have caught off-by-one errors in prefix-sum code this way that no amount of staring would have found.
So the process has three parts. Write the obvious solution and state its cost out loud. Audit it for waste. Apply the specific tool that removes that specific waste. The rest of this essay is about the middle step, because that is the one nobody teaches.
How do you find the wasted work in a brute force solution?
Look at the innermost loop and ask four questions about it: what does it recompute, what does it learn and then discard, which candidates can it never choose, and what structure in the input is it ignoring. Whichever question gets a yes tells you which tool to reach for.
Here is the framing I use. Picture a courier sent to a warehouse once per order, even when forty orders on the same morning want the same crate. Each trip is correct. The courier never delivers the wrong thing. But the courier carries no clipboard, so nothing learned on trip one helps on trip two. Brute force is the courier without a clipboard. Optimization is deciding what to write on the clipboard: a running tally, a list of crates already fetched, a note that crates on the left shelf are all too heavy, a rule that orders are filled in shelf order. Every optimization technique in the standard curriculum is a kind of clipboard.
The four questions map onto four kinds of waste.
- Recomputation. Iteration j+1 redoes most of what iteration j did. A window sum recalculated from scratch, a recursive call with the same arguments for the tenth time. The clipboard entry is a stored result: a running total, a prefix array, a memo table.
- Discarded knowledge. The loop scans for something and forgets what it saw on the way. Scanning the whole array to ask whether a value exists, then scanning again for the next value. The clipboard entry is an index: a hash set or map built once.
- Impossible candidates. The loop evaluates options that cannot win. A partial path already costing more than the best complete path, a pair of indices whose sum is already too large. The clipboard entry is a bound: pruning, a heap holding only the best k, a monotonic structure that evicts losers.
- Ignored structure. The input is sorted, bounded, monotone, or symmetric, and the loop treats it as arbitrary. The clipboard entry is a precondition you exploit: binary search, two pointers, sorting first.
Notice that none of these questions mention the problem's topic. They apply to arrays, graphs, strings and trees alike, and that is why this audit transfers where memorised solutions do not. If you want the larger catalogue of where these shapes show up, recognise the shape, not the problem goes deeper on the same instinct.
How does a brute force go from O(n^3) to O(n) in practice?
It goes in two cuts, each removing one kind of waste. To see it with real numbers, take a problem I like for this: given an integer array that may contain negatives, count the contiguous subarrays whose elements add up to exactly k.
Use the array [3, 4, 7, 2, -3, 1, 4, 2] with k = 7. The answer is 4: the subarrays [3, 4], [7], [7, 2, -3, 1] and [1, 4, 2]. Now scale the idea up to n = 20,000 elements, which is a typical size where the choice of algorithm decides everything.
The brute force enumerates every start i and end j, sums the slice, and compares it with k.
def count_cubic(a, k):
n = len(a)
count = 0
for i in range(n):
for j in range(i, n):
if sum(a[i:j + 1]) == k:
count += 1
return countCount the cost honestly. There are n(n+1)/2 subarrays, which is about 200 million for n = 20,000. Each one costs its own length in additions, and the total across all subarrays is n(n+1)(n+2)/6, roughly 1.33 trillion additions. At a generous billion simple operations per second in a compiled language, that is about 22 minutes. In Python it is days. The code is correct and completely unusable.
Now audit. The inner call to sum recomputes. When j moves from 5 to 6, the slice a[i:7] shares six of its seven elements with a[i:6], and the code adds all of them again. That is recomputation, so the clipboard entry is a running total.
def count_quadratic(a, k):
n = len(a)
count = 0
for i in range(n):
total = 0
for j in range(i, n):
total += a[j]
if total == k:
count += 1
return countEach subarray now costs one addition instead of its length. The work drops from 1.33 trillion to 200 million operations, a factor of about 6,700 from changing three lines. In C++ that finishes in a fraction of a second; in Python it is around 20 seconds, still too slow for most judges but no longer absurd.
Audit again. What does the remaining double loop actually do? For a fixed end j, it tries every start i and checks whether the sum from i to j equals k. Write prefix[x] for the sum of the first x elements. The sum from i to j is prefix[j+1] minus prefix[i], so the check is whether prefix[i] equals prefix[j+1] minus k. For the example, the prefixes are 0, 3, 7, 14, 16, 13, 14, 18, 20. At the final prefix, 20, we need an earlier prefix equal to 13, and there is exactly one, so that end contributes one subarray, [1, 4, 2].
That is the discarded-knowledge pattern. The inner loop is a search for a specific value among earlier prefixes, and it rescans them every time. Remember them in a hash map from prefix value to how many times it has appeared, and each search becomes one lookup.
def count_linear(a, k):
seen = {0: 1}
running = 0
count = 0
for x in a:
running += x
count += seen.get(running - k, 0)
seen[running] = seen.get(running, 0) + 1
return countNow the loop makes 20,000 passes, each with a constant number of operations on average. From 1.33 trillion to roughly 20,000 times a small constant: seven or eight orders of magnitude, and the code is shorter than the one we started with. The price is O(n) extra memory for the map, which at 20,000 integers is a few hundred kilobytes.
One detail deserves a sentence because it trips people up. Many readers see a subarray-sum problem and reach for a sliding window. With negative numbers the window cannot be trusted, since adding an element can lower the sum and removing one can raise it, so the shrink-when-too-big rule breaks. The prefix map has no such assumption. The audit found the right tool precisely because it ignored the topic label and looked at the waste. The same idea is covered in prefix sums, and you can practise it directly on Subarray Sum Equals K.
Which optimization fits which kind of waste?
Match the waste you found to the tool in the table below; the gain is usually a whole factor of n or a factor of n over log n, not a constant.
| Kind of waste | Symptom in the brute force | Typical tool | Typical gain | Cost you pay |
|---|---|---|---|---|
| Recomputed subresults | Inner loop re-sums or re-solves the same thing | Running total, prefix array, memoization | One factor of n, or exponential to polynomial | O(n) memory |
| Rescanning for membership or a complement | Inner loop searches for a value | Hash set or hash map | O(n) per query to O(1) average | O(n) memory, hashing overhead |
| Rescanning for the best element | Inner loop finds a min, max or top k | Heap, monotonic stack or deque | O(n) per query to O(log n) or amortized O(1) | Extra structure, harder invariants |
| Unused order or monotonicity | Candidates are tried in arbitrary order | Sort first, binary search, two pointers | O(n^2) to O(n log n) or O(n) | O(n log n) sort, may lose original indices |
| Dead branches | Search continues past hopeless states | Pruning with a bound | Large but input dependent; worst case unchanged | Gains hard to predict |
Two comments on the table. First, the gains in the last row are different in kind from the others: pruning improves typical runs but rarely changes the worst-case bound, so I do not count it as an asymptotic fix. Second, several rows can stack. The classic Two Sum is the second row alone: one pass, one map, O(n) instead of O(n^2). 3Sum uses the fourth row: sort once, then a pair of converging pointers replaces the innermost search, so O(n^3) becomes O(n^2). The reasoning is the same each time. Find what the loop is wasting, then pick the row.
How do you know when to stop optimizing?
Stop when the worst-case operation count fits the input limits with a safe margin, and not before you have confirmed correctness against the slow version.
Use rough budgets. A compiled language does about 10^8 to 10^9 simple operations per second, and Python manages perhaps 10^7. So with n = 10^5, an O(n^2) solution means 10^10 operations and fails everywhere, while O(n log n) means about 1.7 million and passes in any language. With n = 2,000, O(n^2) is 4 million operations and is perfectly fine, and replacing it with a hash map buys you nothing but risk. Constraints are information about which row of the audit you actually need. If you are fighting a time limit and are unsure where the time goes, why does my solution get time limit exceeded walks through diagnosis in more detail.
There is a second stopping rule that matters in interviews. Each additional optimization costs you clarity. The prefix-map solution above is only five lines, but it is harder to explain than the quadratic one, and the interviewer is grading your explanation as much as your code. A reasonable sequence is to say the brute force and its cost aloud, name the waste you see, move to the fix, and then state the new time and space. That narration is the optimization process made visible, and it scores better than silently producing the final answer.
What mistakes make optimization go wrong?
The common ones are optimizing the wrong loop, adding a structure that does not change the complexity, and skipping the comparison with the slow version.
The first is easy to do. If the outer loop runs n times and the inner runs n times but each iteration of the inner loop also calls a linear-time helper, your real cost is n cubed, and speeding up the loops themselves will not help. Cost the whole body, as we did with the slice sum above, which looks like one operation and is actually a loop.
The second is subtler. Sorting inside a loop to get order adds a log factor to work you were already repeating. Building a hash set inside the loop it was meant to replace rebuilds the index every time and gives you O(n^2) again with worse constants. The structure has to be built once, outside the loop whose waste it is meant to remove, and only then does the lookup pay for itself.
The third is the one I see most. People write the fast version, run the two or three sample cases, see matching answers, and submit. Samples rarely contain the cases that break prefix-map code: a k of zero, an array of all zeros, a single element, negative values. A random test of a thousand arrays of length 0 to 10 with values from -3 to 3, run through both the cubic and the linear version, covers those in a second. When k is zero, for example, the map must be seeded with {0: 1} so that a prefix that equals zero on its own counts as a valid subarray, and that is exactly the kind of detail a random comparison finds immediately.
Frequently asked questions
Should I always write the brute force first in an interview?
Almost always, at least aloud. It proves you understand the problem, gives you a correct baseline, and exposes the waste you will remove. The exception is when the optimal approach is genuinely obvious to you, in which case spending five minutes on a worse one is theatre.
Is memoization the same as optimizing a brute force solution?
It is one form of it, aimed at recomputation: you remember results of repeated subproblems so each is solved once. It does not help with the other kinds of waste, such as rescanning for a value or ignoring sorted order, which need an index or a different traversal. See memoisation vs tabulation for the two main ways to do it.
What if I cannot see any repeated work in my brute force?
Then check the last two questions: whether any candidates are impossible, and whether the input has order or bounds you are not using. If the answers are still no, try sorting the input or fixing one variable and asking what the remaining part of the problem looks like; that often turns a hidden search into a visible one.
The habit to build is small: before reaching for any named pattern, read your slow loop and say what it repeats. To practise that exact audit on a problem where the answer is not a sliding window, work through Subarray Sum Equals K and write all three versions yourself.