Building logic from brute force
Start with the simplest correct idea, even a slow one. Then find the repeated or wasted work inside it, and remove that work step by step until it is fast enough.
How to recognise it
- You have no idea where to start. The brute force is always a start.
- Your first idea checks every pair, every subarray or every subset, and the limits are large.
- You notice the same calculation being redone inside a loop.
- An interviewer asks "can you do better?"
The idea in one picture
Think of finding your keys. The brute force is to search every room, every drawer, every pocket. It always works, and it is slow. Then you notice things: "I always drop them near the door", "I already checked this drawer". Each observation removes wasted searching. That is how most clever algorithms are found: not out of thin air, but by watching a slow method and cutting out its waste.
The process
1. Restate the problem in your own words, with a small example.
2. Write the simplest correct method. Do not worry about speed.
3. Measure its Big-O against the limits.
4. If too slow, look inside it for repeated or wasted work.
5. Remove that work and measure again. Repeat until it fits.
Where waste hides
| What you see in the brute force | Common fix |
|---|---|
| The same sum or count is recomputed inside a loop | Keep it running, or precompute (prefix sums) |
| For each item, you scan back looking for a partner | Remember what you have seen (hash set or map) |
| You test every value one by one in a sorted range | Binary search |
| You try every pair in an array you could sort | Sort, then move two pointers |
| Recursion solves the same small problem many times | Remember the answers (dynamic programming) |
A guided example
Problem: does any pair of numbers in an array add up to a target?
- Brute force: check every pair
(i, j). Correct, O(n²). - Look for waste: for each
nums[j], we scan everything before it, looking fortarget - nums[j]. That scan repeats work: we keep looking at the same earlier numbers. - Remove it: keep the earlier numbers in a hash set. The scan becomes one look-up.
seen = empty set
for x in nums:
if target - x is in seen:
return true
add x to seen
return false
That is O(n). The guided pages on this site follow the same path: brute force first, then the key insight, then the plan.
Common mistakes
- Skipping the brute force and getting stuck looking for the clever answer.
- Optimising before the brute force is correct, then having nothing to compare against.
- Stopping at "this is too slow" without asking which part is slow.
- Optimising further than the limits need, which adds bugs for no benefit.
Problems
No problems listed for this pattern yet.