Lesson 7 of 27From idea to plan
Brute Force First
State the simplest correct solution, compute its cost, and use it as a reference to test your faster idea.
You can now read a problem and say exactly what it asks, what it allows and where it breaks. The next step is a plan. When you see a problem, there is a pull to find the clever solution immediately. Resist it for one minute. The brute force (the most direct solution that is obviously correct, however slow) is the fastest way to prove you understand the problem, it gives you a cost to beat, and it becomes the reference you test your clever solution against. Sometimes it is the answer.
What a brute force is
Almost every brute force has the same shape: list every candidate answer, check each one, keep the best. That shape is called generate and test.
- Two Sum: every pair
(i, j)is a candidate. Check if it sums to target. - Longest substring without repeats: every substring is a candidate. Check if it has repeats.
- Best time to buy and sell: every
(buy, sell)withbuy < sell. Keep the biggest difference. - Subsets with some property: every one of the 2ⁿ subsets. Check the property.
If you cannot write the brute force, you do not understand the problem yet. That alone makes it worth doing.
Every pair (i, j) with i < j is a candidate. 2 + 11 = 13. No.
Enumerate the search space out loud
Before you judge a brute force, name exactly what it enumerates and how many candidates that is. Four shapes cover most problems, and their counts are worth knowing by heart:
| Candidates | How you loop | Count for n items | n = 20 |
|---|---|---|---|
Pairs i < j | two nested loops | n(n − 1)/2 | 190 |
Contiguous subarrays [i..j] | i then j >= i | n(n + 1)/2 | 210 |
| Subsets | include or skip each item | 2ⁿ | about 10^6 |
| Orderings | pick each next item | n! | about 2.4 · 10^18 |
Two traps hide in this table. First, a subarray is contiguous and there are only about n²/2 of them, while a subsequence keeps order but may skip items, and there are 2ⁿ. Mixing them up turns a fine O(n²) idea into an impossible O(2ⁿ) one, or the reverse. Second, the count of candidates is not the total cost. Checking each subarray by summing it costs up to n more, so the naive version is O(n³) even though there are only n² candidates.
Saying the count is also how you spot the fix later. "There are n² subarrays and I sum each one from scratch" is the sentence that leads straight to prefix sums in Find the Bottleneck.
How many contiguous subarrays does this count for n = 4?
n = 4 print(sum(1 for i in range(n) for j in range(i, n)))
Counting, deciding, optimising
The question type changes what the brute force must do and when it may stop.
- Decision ("does any pair sum to target?"): stop at the first hit. The worst case is still every candidate, but the average can be much better.
- Optimisation ("the longest", "the minimum cost"): you must see every candidate, or prove the ones you skip cannot win. Keep a running best.
- Counting ("how many subarrays sum to k?"): you must count every valid candidate exactly once. You cannot stop early, and duplicates are the classic bug. If the answer can be huge, the problem usually says "return it modulo 10^9 + 7", which is itself a hint that the count is too big to enumerate and you need DP or combinatorics.
Name the type when you state the brute force. It tells the interviewer you know what "correct" means here, and it tells you whether an early exit is legal.
Always state it, with its cost
In an interview, say the brute force out loud even if you already see the better solution. It takes twenty seconds and earns real credit: you have a correct answer on the table, and the interviewer can see you reasoning from it.
Then compute its cost against the constraints. "Every pair is n²/2 checks. With n up to 10^4 that's 5 · 10^7, which is borderline, and with 10^5 it's 5 · 10^9, too slow." Now you know exactly how much better you need to be, and the next lesson shows how to find where the waste is.
How many pairs does the brute force check for 5 numbers?
n = 5
count = 0
for i in range(n):
for j in range(i + 1, n):
count += 1
print(count)Match each problem's brute force to its cost.
Use it as a correctness reference
Your clever solution has more ways to be wrong than the brute force does. So keep the brute force and compare them on many random small inputs. This is called a stress test, and competitive programmers rely on it.
Press Run (⌘ Enter) to see what happens.Now break fast on purpose: change best = max(best, p - lowest) to best = p - lowest and run it again. The stress test finds a mismatch within a few trials and prints the exact small input that fails. That input is your debugging case.
Put the stress-test routine in order.
- Tap the steps below in the right order.
When brute force is the answer
Sometimes the constraints say "brute force is expected". Recall the constraint table: n ≤ 10 allows n!, n ≤ 20 allows 2ⁿ. Then the job is not to avoid trying everything; it is to try everything cleanly, usually with backtracking.
- Subsets of up to 10 numbers: 2^10 = 1024 subsets. List them all.
- Permutations of up to 6 numbers: 720 orderings.
- N-Queens with n up to 9: try each row's queen position, back up on conflict.
- Word Search on a small board: try every start cell and every path, with pruning.
And when the output itself is huge ("return all subsets"), no algorithm can beat the output size. Brute force is optimal.
nums', with 0 <= nums.length <= 10. What should you aim for?Brute force plus pruning
Between "try everything" and "find the clever algorithm" sits a middle option that interviews accept for small inputs: try everything, but abandon a branch the moment it cannot lead to a valid or better answer. That is backtracking with pruning.
- Feasibility pruning: in Combination Sum with sorted candidates, once the running total passes the target, every larger candidate will too, so you
breakinstead of continuing. - Bound pruning: in an optimisation search, if the best this branch could possibly reach is worse than the best you already have, stop. This is branch and bound.
- Symmetry pruning: in Subsets II or Permutations II, skip a value equal to the one you just tried at the same depth, so you never build the same answer twice.
Pruning rarely changes the worst-case Big O, and you should say so: "worst case is still 2ⁿ, but sorting lets me cut branches early, and with n ≤ 15 it is fine either way." Interviewers accept this when the constraints are small (roughly n ≤ 10 for orderings, n ≤ 20 for subsets). With n = 10^5 no amount of pruning saves an exponential search. Decoding Backtracking and Heaps has the full template.
A worked ladder: 3Sum
"Find all unique triplets that sum to zero, n ≤ 3000." Watch how each rung comes from naming the waste in the rung below.
- Brute force, O(n³): every triple
i < j < k, keep the sorted triple in a set to remove duplicates. With n = 3000 that is about 4.5 · 10^9 triples. Too slow, but obviously correct. - Waste: for a fixed pair, the third number is fully determined (
-(a + b)). Scanning for it is a repeated lookup. - O(n²) with a hash set: fix
i, then walkjand ask a set whether the needed value has been seen. Correct, but deduplicating triples gets fiddly. - O(n²) with sort and two pointers: sort once (O(n log n), dominated by the rest), fix
i, and moveloandhitoward each other. Sorting also makes duplicates adjacent, so you skip them with one comparison. Same Big O as the hash version, O(1) extra space beyond the sort, and much cleaner dedupe.
The stress test from earlier is exactly how you check the dedupe logic, which is where most 3Sum bugs live.
Press Run (⌘ Enter) to see what happens.Try deleting the while lo < hi and nums[lo] == nums[lo - 1] loop. The stress test finds an input with a duplicated triplet almost immediately. Small value ranges like -4..4 are deliberate: they force duplicates, which is where the bugs are. Testing Your Own Solution covers how to pick inputs like this on purpose.
Practice
Here the brute force is the intended solution. Generate every subset cleanly.
Subsets
Given a list of distinct integers nums, return every possible subset (the power set). Include the empty subset and the full list. The subsets, and the numbers inside each one, can be in any order, but no subset may appear twice.
[1, 2, 3] → [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
[0] → [[], [0]]Constraints
0 <= nums.length <= 10-10 <= nums[i] <= 10- All the numbers in
numsare distinct.
- brute force
- The most direct solution that is obviously correct: list every candidate answer and check each one.
- generate and test
- The shape of most brute forces: enumerate candidates (pairs, substrings, subsets), test each, keep the best.
- stress test
- Compare a fast solution with the brute force on many small random inputs to find a failing case.
- cost to beat
- The brute force's complexity plugged into the constraints. It tells you how much faster you need to be.
- search space
- The full set of candidates a brute force enumerates, such as all pairs, subarrays, subsets or orderings.
- pruning
- Abandoning a branch of a search as soon as it cannot produce a valid or better answer.
- output-bound
- When the answer itself has 2ⁿ or n! items, listing them is the lower bound, so brute force is optimal.