The slow answer first
After this: Write the brute force for two sum, count the pairs it checks, and say why it is worth writing.
On this page · 7 sections · 3 checks
In lesson 1 you found the answer for [3, 2, 4] by looking at the numbers. A program cannot look. What is the most direct thing it can do? Add up every pair of numbers until one pair makes the target.
That is step 3: the slow, obvious answer, the brute force. It is often the first thing you think of, and it is worth writing down.
Every pair, by hand
Take [3, 2, 4] and target 6 again. Pair each position with every position after it:
- Positions 0 and 1: 3 + 2 = 5. Not 6.
- Positions 0 and 2: 3 + 4 = 7. Not 6.
- Positions 1 and 2: 2 + 4 = 6. Found: return
[1, 2].
That took 3 checks. Now take a worse case: [2, 7, 11, 15] with target 26. Only 11 + 15 makes 26, and it is the last pair. The program checks all 6 pairs of four items before it returns [2, 3].
The code
Two loops do this. The outer loop picks the first item, i. The inner loop picks every item after it, j.
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 []
print(two_sum_brute([3, 2, 4], 6))[1, 2]
import java.util.Arrays;
public class Main { static int[] twoSumBrute(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } return new int[0]; }
public static void main(String[] args) { System.out.println(Arrays.toString(twoSumBrute(new int[] {3, 2, 4}, 6))); }}[1, 2]
- The outer loop gives
ieach position in turn. - The inner loop starts
jati + 1, so a position is never paired with itself, and each pair is tried once. - If the two numbers add up to the target, the function returns their positions at once.
- If the loops end without a match, no pair works, and the function returns the empty list.
Step through it below and count how many times the if line runs.
- Run the programRun it and step through. Watch the boxes i and j in the Variables panel. Each time the if line is highlighted, the program adds up one pair. Count those times.
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 []
print(two_sum_brute([3, 2, 4], 6))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Counting the cost
The of a program is how its work grows as the input grows. For the brute force, the work is the number of pairs. With n items, the first item is paired with n − 1 others, the next with n − 2, and so on. That adds up to n(n − 1)/2 pairs:
| Items (n) | Pairs, n(n − 1)/2 |
|---|---|
| 4 | 6 |
| 10 | 45 |
| 1,000 | 499,500 |
| 100,000 | 4,999,950,000 |
This cost is written O(n²), which means the work grows with the square of the list's length: double the list and the work is about four times as large. The arrays tutorial explains the O( ) way of writing cost in Counting steps, and the two-pointers tutorial counts these same pairs in Trying every pair.
A computer does a few thousand checks in far less than a second. Nearly five billion checks would take minutes in Python. A problem that allows 100,000 items usually expects an answer within a second or so.
Why write the slow answer at all?
- It is correct, and you can trust it, because it tries everything.
- It gives you something to test the fast answer against in lesson 5.
- It shows the interviewer that you can solve the problem before you make it fast. A correct slow answer is worth more than a fast answer that does not work.
Run it
The block below runs Python in your browser. Java does not run here: when Java is selected, the Java code is shown for reading, and you can step through it in the trace above or paste it into a Java tool on your computer.
This version adds a counter, checks, that goes up by one for every pair the program adds up. It prints the counts for the two examples above, then the pair counts from the table.
Try your own list: add a line that calls the counting function on six numbers with no answer, and check that it prints 15.
Check yourself
The slow answer runs on [3, 2, 4] with target 6. Which pairs of positions does it add up, in order, before it returns?
The slow answer with a counter, on [2, 7, 11, 15] and target 9. What does this print?
def count_checks(nums, target): checks = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): checks += 1 if nums[i] + nums[j] == target: return checks return checks
print(count_checks([2, 7, 11, 15], 9))public class Main { static int countChecks(int[] nums, int target) { int checks = 0; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { checks += 1; if (nums[i] + nums[j] == target) { return checks; } } } return checks; }
public static void main(String[] args) { System.out.println(countChecks(new int[] {2, 7, 11, 15}, 9)); }}A list has 10 items and no pair adds up to the target. How many pairs does the slow answer add up?
Honesty notes
- Write the brute force with two loops, the inner one starting after the outer one, so each pair is tried once.
- Count the pairs it checks: 3 for [3, 2, 4] with target 6, all 6 for [2, 7, 11, 15] with target 26.
- Say the cost: n(n − 1)/2 pairs, which is O(n²), so doubling the list makes the work about four times as large.
- Say why the slow answer is worth writing: it is correct, it gives you something to test against, and it shows you can solve the problem.