Sub topic 1
Why Start with Brute Force
Prerequisites
This chapter assumes you can write functions, loops, and recursion in Python. It also assumes you know arrays, lists, and dictionaries, and can read Big-O notation such as O(n) and O(n^2).
Why Start with Brute Force
A brute-force solution tries every possible candidate and checks each one against the problem's condition. It is rarely the fastest approach. It is usually the easiest one to prove correct. Writing it first gives you three things:
- A working answer you can submit or ship if the inputs are small.
- A reference you can test faster code against later.
- A clear view of where the time goes, which points toward optimizations.
Defining What You Are Searching Through
Before writing any loop, state the search space: the full set of candidate solutions. Then state the check that decides whether a candidate is valid.
Take the two-sum problem: given a list nums and a target, find indices i < j with nums[i] + nums[j] == target.
| Part | Two-sum |
|---|---|
| Candidate | A pair of indices (i, j) with i < j |
| Search space size | n(n-1)/2 pairs |
| Check | `nums[i] + nums[j] == target` |
Pairs and Tuples with Nested Loops
Nested loops enumerate pairs. Starting the inner loop at i + 1 visits each unordered pair once and never pairs an index with itself.
def two_sum_brute(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
print(two_sum_brute([2, 7, 11, 15], 9)) # (0, 1)
print(two_sum_brute([3, 3], 6)) # (0, 1)
print(two_sum_brute([1, 2], 10)) # NoneFor triples, add a third loop starting at j + 1. Each extra loop multiplies the cost by about n.
Getting It Right Before Getting It Fast
Make sure the brute force handles edge cases before you think about speed. These are the common mistakes:
- Self-pairing: starting
jat0or atiletsnums[i] + nums[i]match by mistake. - Empty or single-element input: the loops should run zero times and return
Nonewithout crashing. - Duplicates:
[3, 3]with target 6 must succeed. - Negatives and zero: never assume the values are positive unless the problem says so.
Exercise
For three-sum (find i < j < k with nums[i] + nums[j] + nums[k] == target), what are the search space, its size, and the loop bounds?
Show answer
The candidates are index triples with i < j < k, and there are n(n-1)(n-2)/6 of them, which is O(n^3). Use three nested loops: i over range(n), j over range(i + 1, n), and k over range(j + 1, n).