Sub topic 2
Defining What You Are Searching Through
This chapter assumes you can write Python functions, loops, and generators, and that you know lists and dictionaries. You should also be able to read simple Big-O expressions such as O(n²). Later chapters cover the specific enumeration techniques (nested loops, bitmasks, permutations) and how to estimate cost against input limits. This chapter covers the step that comes before all of them: deciding exactly what the brute force enumerates.
The Working Model: Candidates, Checks, and Objectives
Every brute-force solution answers three questions, whether or not the author wrote them down:
- What is a candidate? A candidate solution is one concrete thing that might be the answer, such as a pair of indices, a subset of items, an ordering of cities, or an integer value.
- Is this candidate valid? A validity check is a function that takes one candidate and returns whether it satisfies the problem's constraints.
- Which valid candidate is best? An objective is the quantity you minimize or maximize. Some problems don't have one, and any valid candidate will do.
The search space is the set of all candidates your code will generate. Brute force is correct when two conditions hold. The search space must contain every candidate that could be the answer, which is called completeness. And the check and objective must be evaluated correctly on each one.
You can write this model as a generic function. Real solutions usually inline it, but the generic form makes the three parts explicit:
def brute_force(candidates, is_valid, score=None):
"""Return the first valid candidate, or the valid candidate with the
lowest score if a score function is given. Return None if none is valid."""
best = None
for c in candidates:
if not is_valid(c):
continue
if score is None:
return c
if best is None or score(c) < score(best):
best = c
return best
def index_pairs(n):
for i in range(n):
for j in range(i + 1, n):
yield (i, j)
nums = [3, 8, 2, 5]
target = 7
print(brute_force(index_pairs(len(nums)),
lambda p: nums[p[0]] + nums[p[1]] == target))
# (2, 3)Two-sum fits this model directly. A candidate is a pair of indices (i, j) with i < j. The check is nums[i] + nums[j] == target. There is no objective. The i < j constraint is part of the search space definition. It leaves out pairs that use the same element twice, and it leaves out mirror-image duplicates.
Write the Search Space Down Precisely
Before coding, write one sentence of the form "a candidate is a __ such that _, and there are about __ of them." For example:
- "A candidate is a pair of indices
(i, j)with0 ≤ i < j < n. There are n(n−1)/2 of them." - "A candidate is a subset of the n items. There are 2ⁿ of them."
- "A candidate is an ordering of cities 1..n−1 after fixing city 0 as the start. There are (n−1)! of them."
- "A candidate is an integer capacity between
max(weights)andsum(weights). There aresum − max + 1of them."
This sentence does three jobs. It tells you which enumeration technique to use. It tells you roughly how expensive the search is, which a later chapter turns into a go or no-go decision. And it gives you something concrete to check completeness against.
| Problem shape | Natural candidate | Search space size | Typical generator |
|---|---|---|---|
| Find two elements with a property | Index pair `i < j` | n(n−1)/2 | Two nested loops |
| Find a contiguous range | `(start, end)` with `start ≤ end` | n(n+1)/2 | Two nested loops |
| Choose some items | Subset | 2ⁿ | Bitmask or recursion |
| Order or arrange items | Permutation | n! | `itertools.permutations` |
| Find a numeric answer | Integer in `[lo, hi]` | hi − lo + 1 | `range(lo, hi + 1)` |
| Assign one of k labels to each item | Tuple of labels | kⁿ | `itertools.product` |
The Same Problem, Different Search Spaces
One problem can usually be modeled with more than one candidate representation, and the sizes can differ by orders of magnitude. Choose the smallest space that is still complete.
Take the maximum subarray sum problem: find the contiguous run of elements with the largest sum. A careless model treats a candidate as "any subset of positions" and filters out the non-contiguous ones. That space has 2ⁿ candidates. Contiguity means a candidate is fully described by its endpoints, so the right space is (start, end) pairs, about n²/2 of them.
def max_subarray_brute(nums):
# Candidate: (start, end) with 0 <= start <= end < n.
# Objective: maximize sum(nums[start:end + 1]).
if not nums:
return None
best = nums[0]
for start in range(len(nums)):
running = 0
for end in range(start, len(nums)):
running += nums[end]
best = max(best, running)
return best
print(max_subarray_brute([2, -5, 3, 4, -1, 2])) # 8 (3 + 4 - 1 + 2)The rule generalizes. Let the problem's structure decide what a candidate is, and turn constraints into the shape of the generator where you can, so you aren't generating candidates only to reject them. A constraint built into the generator costs nothing per candidate. A constraint applied as a filter still costs one generation and one check for every rejected candidate.
Searching the Answer Space Instead of the Input
Sometimes the natural candidate is the answer itself rather than a structure built from the input. Problems that ask for "the smallest X such that…" or "the largest X such that…" often work best this way.
Here is an example. Packages with weights weights must be shipped in order over days days. Each day the ship carries a contiguous run of packages whose total weight is at most its capacity. Find the minimum capacity that works.
One model enumerates every way to split the list into days contiguous groups. That is complicated, and there are many such splits. The simpler model treats a candidate as a capacity value. The check is: "with this capacity, does a greedy day-by-day loading finish within days?"
def days_needed(weights, cap):
days, load = 1, 0
for w in weights:
if load + w > cap:
days += 1
load = 0
load += w
return days
def min_capacity(weights, days):
# Candidate: integer capacity in [max(weights), sum(weights)].
# Enumerated in increasing order, so the first valid one is the minimum.
for cap in range(max(weights), sum(weights) + 1):
if days_needed(weights, cap) <= days:
return cap
print(min_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) # 15The bounds of the answer space come from reasoning about the problem, and you should write that reasoning down:
- Any capacity below
max(weights)cannot carry the heaviest package, so no smaller value can be valid. - A capacity of
sum(weights)ships everything on day one, so at least one valid value always exists. The loop therefore always returns. This assumesweightsis non-empty anddays ≥ 1.
The order of enumeration also matters here. Because capacities are tried in increasing order, the first valid one is the minimum, so no separate objective is needed. If you enumerated in a different order, you would have to keep a best-so-far and scan the whole range.
Completeness: Proving You Didn't Miss Anything
Brute force is trusted because it is exhaustive. That trust only holds if the search space really contains the answer. For each solution, you should be able to state in a sentence or two why every possible answer is generated:
- Two-sum: any valid answer is two distinct indices. Sort them so the smaller one comes first, and you get exactly one generated pair
(i, j)withi < j. - Maximum subarray: any contiguous run has a first index and a last index, and the loops generate every such pair.
- Minimum capacity: the answer is an integer, it is at least
max(weights), andsum(weights)is always valid, so the answer lies in the enumerated range.
If you cannot write a sentence like these, the search space is a guess.
Common Errors
| Error | Example | Consequence | Fix |
|---|---|---|---|
| Space too small | `range(i + 1, n - 1)` instead of `range(i + 1, n)` | Misses answers involving the last element | Check the endpoints of every range against the definition |
| Including invalid candidates | `for j in range(n)` in two-sum | Pairs an element with itself (`i == j`) | Encode `i < j` in the generator |
| Duplicate candidates | Both `(i, j)` and `(j, i)` | Doubled work, and double counting in "count the pairs" problems | Generate a canonical form only |
| Wrong representation | Subsets for a contiguous-range problem | Exponential instead of quadratic cost | Let the problem's structure define the candidate |
| Unjustified answer bounds | Starting capacity at 1, or stopping before `sum` | Wasted work, or a `None` result when an answer exists | Derive the bounds and write the reasoning in a comment |
| Wrong search order assumption | Returning the first valid capacity from a descending loop | Returns the maximum, not the minimum | Match the enumeration order to the objective, or track the best |
| Mutating shared state | Reusing one list object as every candidate | Stored candidates change after being recorded | Copy candidates you keep, or use immutable tuples |
Edge Cases Live in the Search Space
Many edge cases come down to the search space being empty or very small:
- With
n = 0orn = 1, there are no index pairs. The function must returnNone(or whatever "no answer" means) rather than crashing. - With the empty subset, decide whether it counts. Should a subset sum target of 0 be satisfied by choosing nothing?
- With a single city, the tour is trivial. Does the problem define its cost as 0?
- If the answer space is empty because
lo > hi, the loop never runs. Make sure the code after the loop handles that.
For each of these, writing the candidate definition precisely forces you to decide. The next chapter puts these definitions into nested loops and shows how to keep them correct.
Exercise
A problem asks: "Given an array of n integers, count the triples of distinct positions whose values sum to zero." State the candidate, the search space constraint that avoids duplicates, and the search space size. Should the generator produce ordered or unordered triples?
Show answer
A candidate is a triple of indices (i, j, k) with 0 ≤ i < j < k < n. The strict ordering i < j < k excludes repeated positions and lists each unordered triple exactly once. The space has n(n−1)(n−2)/6 candidates. The problem counts sets of positions, so the generator should produce unordered triples (the canonical sorted form). Generating ordered triples would count each answer 6 times.
Exercise
You need the largest integer x with x * x <= N, for N >= 0. Define the answer space with justified bounds, and say which direction to enumerate so the first valid candidate is the answer.
Show answer
Candidates are integers in [0, N]. The lower bound 0 always satisfies 0 0 <= N, so an answer exists. Any x > N fails when N >= 1, because then x x > N N >= N, and when N = 0 the answer is 0. Enumerating from N down to 0 and returning the first x with x x <= N gives the largest valid x. (Tighter bounds, such as N // 2 + 1 for N >= 2, also work if you justify them.)
Exercise
A colleague solves "find any subset of items whose weights sum to exactly W" by looping over every permutation of the items and checking each prefix. Is the search space complete? What is wrong with it?
Show answer
It is complete. Every subset appears as a prefix of some permutation. But it is far larger than needed: n! permutations, each with n + 1 prefixes, while there are only 2ⁿ subsets. Each subset is generated many times because order doesn't matter for a sum. Enumerating subsets directly removes the duplication.