Sub topic 2
Defining What You Are Searching Through
This chapter assumes you can write Python functions and loops, know lists and dictionaries, and can read basic Big-O notation such as O(n) and O(n^2).
A brute-force solution only works if you know exactly what it enumerates. Before writing code, describe the search space: the full set of candidate solutions, plus a rule that decides whether a candidate counts as an answer. Many brute-force bugs come from a vague answer to that question. The loop skips some candidates, counts one twice, or checks the wrong condition.
The three parts of a search
Each brute-force solution has three parts:
- Candidates. These are the objects you will generate. A candidate could be a pair of indices, a subset of items, or an ordering of cities.
- Validity check. This is a test that says whether a candidate satisfies the problem's constraints.
- Goal. You either stop at the first valid candidate (a decision or search problem), count all valid candidates (a counting problem), or keep the best one (an optimization problem).
Writing the search space down precisely
Take two-sum: given a list nums and a target, find two distinct positions whose values add up to target. A precise statement of the search space is:
- Candidates: all index pairs
(i, j)with0 <= i < j < n. - Valid:
nums[i] + nums[j] == target. - Goal: return the first valid pair, or
None.
The condition i < j matters. It excludes (i, i), which would use the same element twice. It also excludes (j, i), which repeats a pair you have already checked. Because the description is precise, you know the size of the space: n(n-1)/2 pairs.
The same template covers other problem shapes. Here are three versions that later chapters build on:
| Problem | Candidate | Validity check | Goal | Space size |
|---|---|---|---|---|
| Two-sum | index pair (i, j), i < j | values sum to target | first valid | n(n-1)/2 |
| Subset sum | subset of items | subset sums to target | any valid | 2^n |
| Traveling salesman | ordering of cities | always valid | minimum tour length | (n-1)! |
A reusable shape
When you separate generation from checking, each part is easy to inspect on its own. The sketch below makes the three parts explicit for a counting problem: how many pairs sum to target?
from itertools import combinations
def candidates(nums):
# Every unordered pair of distinct indices, each exactly once.
return combinations(range(len(nums)), 2)
def is_valid(nums, target, pair):
i, j = pair
return nums[i] + nums[j] == target
def count_pairs(nums, target):
return sum(1 for p in candidates(nums) if is_valid(nums, target, p))
print(count_pairs([1, 2, 3, 4, 3], 6)) # (1,3) and (2,4) -> 2Once you have written candidates, check it on a tiny input. Print the candidates for n = 3 and confirm you get exactly (0,1), (0,2), (1,2).
Common errors
- Wrong candidate type. Enumerating values when the answer needs indices, or the reverse.
- Accidental duplicates. Using
range(n)for both loops counts every pair twice and includes(i, i). - Missing candidates. Off-by-one bounds such as
range(n - 1)for the inner index drop the last element. - Checking a constraint the problem doesn't have, or forgetting one it does have, such as "non-empty subset".
Exercise
You must find the longest contiguous sublist of nums whose sum is zero. State the candidates, the validity check, the goal, and the size of the search space for a list of length n.
Show answer
Candidates are all index ranges (i, j) with 0 <= i <= j < n, each meaning the sublist nums[i..j]. A range is valid when sum(nums[i:j+1]) == 0. The goal is optimization: keep the valid range with the largest j - i + 1. There are n(n+1)/2 candidates.
Exercise
A friend enumerates two-sum candidates with for i in range(n): for j in range(n): and checks nums[i] + nums[j] == target. Give an input where this returns a wrong answer.
Show answer
nums = [3], target = 6. The pair (0, 0) passes the check, but it uses one element twice, so the correct answer is None. The fix is to restrict the loops to j > i.