Skip to content

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.

19 min read0/7 questions

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) with buy < 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.

Brute force Two Sum: check every pair
2
0
↑i
11
1
↑j
7
2
15
3
target = 9sum = 13

Every pair (i, j) with i < j is a candidate. 2 + 11 = 13. No.

1/3

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:

CandidatesHow you loopCount for n itemsn = 20
Pairs i < jtwo nested loopsn(n − 1)/2190
Contiguous subarrays [i..j]i then j >= in(n + 1)/2210
Subsetsinclude or skip each item2ⁿabout 10^6
Orderingspick each next itemn!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.

Predict the outputPython

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)))
Need a nudge? Hints walk you through it.

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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each problem's brute force to its cost.

Choose an item, then its match on the other side.

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.

Python
import random def brute(prices): best = 0 for i in range(len(prices)): for j in range(i + 1, len(prices)): best = max(best, prices[j] - prices[i]) return best def fast(prices): lowest, best = prices[0], 0 for p in prices[1:]: best = max(best, p - lowest) lowest = min(lowest, p) return best for trial in range(1000): prices = [random.randint(0, 10) for _ in range(random.randint(1, 6))] if brute(prices) != fast(prices): print("Mismatch on", prices, brute(prices), fast(prices)) breakelse: print("1000 random tests agree")
Output
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 it in order5 steps

Put the stress-test routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Quick check
'Return every subset of nums', with 0 <= nums.length <= 10. What should you aim for?
Need a nudge? A hint rules out a wrong answer.
Quick check
You see the optimal O(n) solution right away. Should you still mention the brute force?
Need a nudge? A hint rules out a wrong answer.

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 break instead 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.

Quick check
You add pruning to a subset search. What should you say about its complexity?
Need a nudge? A hint rules out a wrong answer.

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.

  1. 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.
  2. Waste: for a fixed pair, the third number is fully determined (-(a + b)). Scanning for it is a repeated lookup.
  3. O(n²) with a hash set: fix i, then walk j and ask a set whether the needed value has been seen. Correct, but deduplicating triples gets fiddly.
  4. O(n²) with sort and two pointers: sort once (O(n log n), dominated by the rest), fix i, and move lo and hi toward 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.

Python
import randomfrom itertools import combinations def brute(nums): found = set() for a, b, c in combinations(nums, 3): if a + b + c == 0: found.add(tuple(sorted((a, b, c)))) return sorted(found) def two_pointer(nums): nums = sorted(nums) out = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue lo, hi = i + 1, len(nums) - 1 while lo < hi: s = nums[i] + nums[lo] + nums[hi] if s < 0: lo += 1 elif s > 0: hi -= 1 else: out.append((nums[i], nums[lo], nums[hi])) lo += 1 while lo < hi and nums[lo] == nums[lo - 1]: lo += 1 hi -= 1 return out print(two_pointer([-1, 0, 1, 2, -1, -4]))for trial in range(2000): nums = [random.randint(-4, 4) for _ in range(random.randint(0, 8))] if brute(nums) != two_pointer(nums): print("Mismatch on", nums) breakelse: print("2000 random tests agree")
Output
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.

ChallengeMedium

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 nums are distinct.
def subsets(nums: list[int]) -> list[list[int]]: # For each number, branch twice: leave it out, or take it. pass
Key terms
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.