Sub topic 4
Getting It Right Before Getting It Fast
This chapter assumes you can write Python functions and loops, read simple assert statements, and recognize Big-O notation such as O(n²). It uses the two-sum brute force from the previous chapter: given a list nums and a target, return two distinct indices whose values add up to the target, or None if no such pair exists.
Why correctness comes first
A brute-force solution checks every candidate in the search space. That makes its logic easy to verify: if the enumeration covers every candidate and the check is right, the answer is right. Faster algorithms skip candidates on purpose, so each one depends on an argument that the skipped candidates could never be the answer. Arguments like that can be wrong in subtle ways.
If you start with a correct brute force, you get three things:
- A working answer you can submit or ship if it turns out to be fast enough.
- A clear statement of what "correct" means, including what the function returns when there is no answer.
- A reference you can compare faster code against later.
An optimized solution that you never confirmed against a simple baseline gives you nothing to fall back on when it fails.
Pin down the specification
Before you write any tests, settle the questions the problem statement may leave open:
| Question | Decision for this chapter |
|---|---|
| Can the same index be used twice? | No, `i != j` |
| What if no pair exists? | Return `None` |
| What if several pairs work? | Any valid pair is acceptable |
| Are negative numbers allowed? | Yes |
| Can the list be empty? | Yes |
The brute force encodes these decisions directly. Starting j at i + 1 rules out reusing an index and also avoids checking the same pair twice.
Edge cases that break solutions
Most wrong answers come from a small set of inputs:
- Empty or single-element lists. No pair exists, so the function must return
Noneand must not crash. - Duplicate values. In
[3, 3]with target 6, the answer uses two different indices that hold the same value. - A value that is half the target. In
[3]or[3, 4]with target 6, the 3 must not be paired with itself. - Negatives and zero.
[-2, 0, 2]with target 0 has the answer(0, 2). - No solution. Inputs with no valid pair at all.
Here is the brute force with a test suite that covers each case:
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
def is_valid(nums, target, result):
if result is None:
return False
i, j = result
return i != j and nums[i] + nums[j] == target
def run_edge_case_tests():
assert two_sum_brute([], 5) is None
assert two_sum_brute([5], 10) is None
assert two_sum_brute([3], 6) is None
assert two_sum_brute([3, 4], 6) is None
assert is_valid([3, 3], 6, two_sum_brute([3, 3], 6))
assert is_valid([-2, 0, 2], 0, two_sum_brute([-2, 0, 2], 0))
assert is_valid([2, 7, 11, 15], 9, two_sum_brute([2, 7, 11, 15], 9))
assert two_sum_brute([1, 2, 3], 100) is None
print("edge cases passed")
run_edge_case_tests()The is_valid helper checks the property you care about, not one specific pair of indices. A later solution may return a different valid pair, and tests that hard-code one answer would reject it for no good reason.
Common errors
- Starting the inner loop at 0 or
i. This lets an element pair with itself, so[3]with target 6 returns(0, 0). - Returning values instead of indices. The function produces something, but it doesn't match the specification.
- Off-by-one ranges.
range(len(nums) - 1)forjskips the last element. - Testing only the sample input. Sample inputs rarely include the empty, duplicate, or no-solution cases.
Exercise
A teammate changes the inner loop to for j in range(len(nums)): and adds the check if i != j. Is the function still correct, and what changed?
Show answer
It is still correct: the i != j check prevents self-pairing, and every unordered pair is still checked. The loop now does about twice as much work, because it visits each pair as both (i, j) and (j, i). It may also return a pair with i > j, so the order of the indices is no longer guaranteed.
Exercise
Write one test input not listed above that would catch a solution which incorrectly pairs an element with itself, while a correct solution returns a valid pair.
Show answer
For example, nums = [5, 1, 4] with target = 10. A buggy solution could return (0, 0) because 5 + 5 = 10. A correct solution finds no pair that sums to 10 and returns None. To get an input where the correct answer is a real pair, use nums = [5, 2, 8] with target = 10: the correct answer is (1, 2), and the buggy version might return (0, 0) first.