Sub topic 4
Getting It Right Before Getting It Fast
This chapter assumes you can write Python functions and loops, know what a list and a dictionary are, and can read simple Big-O claims. It also builds on the previous chapter's nested-loop two-sum solution. That solution is the running example here.
A brute-force solution earns its place by being correct. It is supposed to be slow and obvious. If it is slow and wrong, it is worse than nothing, because every later step trusts it. Later chapters measure faster code against this baseline. This chapter is about making the baseline trustworthy: stating exactly what "correct" means, arguing that the enumeration delivers it, and checking it against the inputs most likely to break it.
Why Correctness Comes First
Changing code is cheaper while the code is simple. A nested loop over pairs has very few moving parts, so a bug in it is easy to see and easy to fix. Once you add a dictionary, a sort, or a memo table, every bug has more places to hide.
There is a second reason. An optimization changes how an answer is found, not what the answer is. If you never pinned down what the answer is, you cannot tell whether an optimization kept it. A verified brute force gives you a fixed reference point for that comparison.
Start with a Precise Specification
"Find two numbers that add up to the target" sounds complete, but it leaves several questions unanswered. Each unanswered question is a place where your code and someone else's expectations can quietly disagree.
| Question | Decision for this tutorial |
|---|---|
| Return values or indices? | Indices `(i, j)` into the original list |
| Can the same element be used twice? | No, `i` must differ from `j` |
| What order are the indices in? | `i < j` |
| What if no pair exists? | Return `None` |
| What if several pairs exist? | Any valid pair is acceptable |
| Can the list be empty or have one element? | Yes, and the answer is `None` |
| Are negatives and zero allowed? | Yes |
| Are duplicate values allowed? | Yes, `[3, 3]` with target 6 gives `(0, 1)` |
The "several pairs" row matters most for later work. The brute force below always returns the pair with the smallest i, and the smallest j for that i. A hash-based version will often return a different pair. If your specification said "return the first pair", those two would disagree and both might look wrong. Saying "any valid pair" up front means tests check validity, not one particular output.
Arguing That the Brute Force Is Correct
Here is the baseline again:
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 NoneA brute-force correctness argument has two halves, and you should be able to state both.
- Soundness. Anything it returns is a valid answer. The only
return (i, j)runs after checkingnums[i] + nums[j] == target. The ranges guarantee0 <= i < j < len(nums), so the indices are distinct, ordered, and in bounds. - Completeness. If a valid answer exists, it finds one. Every pair with
i < jis visited by the loops: the outer loop fixesi, and the inner loop covers every largerj. If the loops finish without returning, no pair satisfied the check, soNoneis the correct answer.
This argument is short because the code is simple. That is the main benefit of brute force. Try writing the same argument for a two-pointer solution on a sorted array and you will need an invariant about which pairs have already been ruled out. The brute force needs nothing beyond "I checked them all."
Common Errors in Brute-Force Code
Brute-force code is simple, but it is not immune to bugs. These mistakes come up again and again.
Using the same element twice
Starting the inner loop at 0 instead of i + 1 looks harmless, and it produces a subtle bug:
def two_sum_buggy(nums, target):
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
return (i, j)
return None
print(two_sum_buggy([3], 6)) # (0, 0) -- wrong, should be None
print(two_sum_buggy([3, 4], 6)) # (0, 0) -- wrong, should be None
print(two_sum_brute([3], 6)) # NoneTypical tests like [2, 7, 11, 15] with target 9 pass with both versions. The bug only shows when some value is exactly half the target. This is why edge cases need to be chosen on purpose rather than taken from the problem statement's example.
Off-by-one ranges
Writing range(len(nums) - 1) for the outer loop is fine, since the last i has no larger j anyway. Writing range(i + 1, len(nums) - 1) for the inner loop is not, because it skips every pair that involves the last element. Each time you shorten a range, ask which candidates you just dropped from the search space.
Returning the wrong shape
Returning (nums[i], nums[j]) instead of (i, j) matches a different specification. Your tests should check the shape of the result as well as whether it is truthy.
Destroying information the answer needs
Sorting the input first is a common reflex, and it breaks index-based answers:
def two_sum_sorted_wrong(nums, target):
nums = sorted(nums)
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_sorted_wrong([5, 1, 4], 5)) # (0, 2): indices into the sorted list
print(two_sum_brute([5, 1, 4], 5)) # (1, 2): 1 + 4 in the original listThe sorted version finds the right values but reports positions in a list the caller never sees. Note that (0, 2) also points at 5 + 4 = 9 in the original list. A brute force should work on the input as given unless the specification says otherwise.
Language-specific hazards
Python integers never overflow. In C++, Java, or Go, nums[i] + nums[j] can overflow a 32-bit integer when values approach two billion. With floating-point values, == can fail because of rounding. Your brute force inherits these hazards, so decide on the arithmetic type as part of the specification.
A Validity Checker
Since several answers can be correct, tests should check validity instead of comparing against one hard-coded output. A checker encodes the specification directly:
def is_valid_answer(nums, target, answer):
if answer is None:
# None is valid only if no pair works.
return all(
nums[i] + nums[j] != target
for i in range(len(nums))
for j in range(i + 1, len(nums))
)
if not (isinstance(answer, tuple) and len(answer) == 2):
return False
i, j = answer
return 0 <= i < j < len(nums) and nums[i] + nums[j] == targetChecking a None answer requires an exhaustive search, which makes the checker itself a small brute force. That is fine. Verifying a claim of "no solution" is often as hard as solving the problem, and slow, obvious checking code is exactly what you want in a test.
Choosing Edge Cases Deliberately
Good edge cases come from the boundaries of the specification, not from random examples. Go through each row of the specification table and ask what input sits right at its edge.
def run_edge_cases(solve):
cases = [
# (nums, target, a valid pair should exist?)
([], 0, False), # empty input
([5], 10, False), # single element, half of target
([3], 6, False), # same-element trap
([3, 4], 6, False), # same-element trap with a second value
([3, 3], 6, True), # duplicates form the only answer
([1, 2, 3], 7, False), # no pair works
([-1, 4, 2], 3, True), # negative values
([0, 0, 0], 0, True), # zeros and repeated answers
([2, 7, 11, 15], 9, True), # the textbook example
([1, 5, 9, 4], 13, True), # answer uses the last element
([1, 1, 1, 1], 2, True), # many valid answers
]
for nums, target, should_exist in cases:
original = list(nums)
answer = solve(nums, target)
assert nums == original, f"input mutated: {original} -> {nums}"
assert is_valid_answer(nums, target, answer), (nums, target, answer)
assert (answer is not None) == should_exist, (nums, target, answer)
print(f"{solve.__name__}: all {len(cases)} edge cases passed")
run_edge_cases(two_sum_brute)Running this prints two_sum_brute: all 11 edge cases passed. Swap in two_sum_buggy and the [3] case fails on the validity assertion. The test also checks that the input list was not modified, which catches in-place sorting, a quieter version of the destroyed-information bug.
Edge Cases Beyond Two-Sum
The same habit carries over to the other enumerations in this tutorial. Each search space has its own boundary inputs.
| Search space | Edge cases to include |
|---|---|
| Pairs and tuples | Length 0, 1, 2; duplicates; answer at the last index |
| Subsets | Empty set as an answer (target 0); target equal to the total; no subset works |
| Permutations | One item; two items; ties in cost; all costs equal |
| Any numeric check | Negatives, zero, largest allowed values, overflow in fixed-width types |
The empty subset deserves special mention. A bitmask loop starting at mask = 0 treats "choose nothing" as a candidate, so subset_sum_exists(items, 0) returns True. Whether that is correct depends on whether your specification allows an empty selection. Decide that before writing the loop.
How This Prepares You for Optimization
Hand-picked edge cases catch the bugs you can think of. They do not catch the bugs you cannot think of. A later chapter fixes that by generating thousands of random small inputs and comparing a fast solution against this brute force. That comparison only means something if the brute force was right in the first place. The specification, the validity checker, and the edge-case suite from this chapter are what make it trustworthy.
Exercise
A teammate writes the outer loop as for i in range(1, len(nums)) and keeps the inner loop as range(i + 1, len(nums)). Which half of the correctness argument fails, and which edge case from run_edge_cases exposes it?
Show answer
Completeness fails: every pair with i = 0 is skipped, so valid answers using the first element are never found. The case [3, 3] with target 6 exposes it, since its only valid pair is (0, 1). The function returns None while a pair exists. [2, 7, 11, 15] with target 9 also fails for the same reason.
Exercise
Why does run_edge_cases check is_valid_answer and existence instead of asserting answer == (0, 1) for [1, 1, 1, 1] with target 2?
Show answer
The specification accepts any valid pair, and that input has six valid pairs. Asserting one exact pair would reject a correct optimized solution that happens to return, say, (0, 1) from a different search order or (2, 3) from a different algorithm. Checking validity plus existence tests the specification itself rather than one implementation's search order.
Exercise
Add one edge case to run_edge_cases that two_sum_sorted_wrong fails but that two_sum_brute passes, and explain which assertion catches it.
Show answer
Use ([5, 1, 4], 5, True). The sorted version returns (0, 2), which refers to sorted positions. In the original list those indices give 5 + 4 = 9, so is_valid_answer returns False and the validity assertion fails. two_sum_brute returns (1, 2), which is valid.