Trying every pair
After this: Count the pairs a loop inside a loop checks, and say why that is O(n²).
On this page · 7 sections · 3 checks
In the last lesson, two pointers found a pair in two tries, and trying the pairs in order took five. This lesson looks closely at that slower way. If you know what the slow way costs, you can see what the better methods save.
The slow way: try every pair
Start with a very small array, [1, 3, 5], and a target of 7. The most direct plan is to try every pair.
- Try 1 + 3 = 4. That is not 7.
- Try 1 + 5 = 6. That is not 7.
- Try 3 + 5 = 8. That is not 7.
No pairs are left, so the answer is no. Three numbers gave three pairs.
This plan of trying every possibility, one after another, is called . The name is not an insult. A brute-force program gives the right answer, and it is often the first thing to write. Its only fault is that it can be slow.
Counting the pairs
To see how slow, we count the pairs. The pair 1 + 3 is the same as 3 + 1, so we count it once.
| Numbers | Pairs | How many |
|---|---|---|
[1, 3] | 1 + 3 | 1 |
[1, 3, 5] | 1 + 3, 1 + 5, 3 + 5 | 3 |
[1, 3, 5, 8] | 1 + 3, 1 + 5, 1 + 8, 3 + 5, 3 + 8, 5 + 8 | 6 |
Now add a fifth price, so that the array is [1, 3, 5, 8, 11]. Here is a tidy way to count: go through the numbers in order, and count how many numbers come after each one.
- 1 has four numbers after it: 3, 5, 8 and 11.
- 3 has three numbers after it: 5, 8 and 11.
- 5 has two numbers after it: 8 and 11.
- 8 has one number after it: 11.
- 11 has none.
That makes 4 + 3 + 2 + 1 = 10 pairs.
Programmers use the letter n for the number of items. Each of the n numbers can pair with n − 1 others, and that counts every pair twice, so the number of pairs is n(n − 1) / 2. For five numbers this gives 5 × 4 / 2 = 10, the same as our count. For a thousand numbers it gives 1,000 × 999 / 2 = 499,500.
What O(n²) means
Look at what happens when the array doubles in size.
| Numbers | Pairs |
|---|---|
| 1,000 | 499,500 |
| 2,000 | 1,999,000 |
| 4,000 | 7,998,000 |
Each time the numbers double, the pairs become about four times as many. This kind of growth is called , said "order n squared". It means that the number of steps grows like n × n, so double the data gives about four times the steps. The notation looks only at how the work grows, so it drops the "divide by 2" from the formula.
Compare this with O(n), which means that the steps grow at the same rate as the data: double the data, double the steps. The lesson Counting steps explains O(1) and O(n) from the start. The rest of this tutorial turns O(n²) work into O(n) work.
The code
This function looks for a pair that adds up to target. It tries every pair of [1, 3, 5, 8, 11], first for a target of 13 and then for a target of 7.
def two_sum_brute(nums, target): checks = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): # every pair once: j is always after i checks += 1 if nums[i] + nums[j] == target: return i, j, checks return -1, -1, checks
i, j, checks = two_sum_brute([1, 3, 5, 8, 11], 13)print(i, j, checks)i, j, checks = two_sum_brute([1, 3, 5, 8, 11], 7)print(i, j, checks)2 3 8 -1 -1 10
public class Main { static int[] twoSumBrute(int[] nums, int target) { int checks = 0; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { // every pair once: j is always after i checks++; if (nums[i] + nums[j] == target) return new int[] {i, j, checks}; } } return new int[] {-1, -1, checks}; }
public static void main(String[] args) { int[] hit = twoSumBrute(new int[] {1, 3, 5, 8, 11}, 13); System.out.println(hit[0] + " " + hit[1] + " " + hit[2]); int[] miss = twoSumBrute(new int[] {1, 3, 5, 8, 11}, 7); System.out.println(miss[0] + " " + miss[1] + " " + miss[2]); }}2 3 8 -1 -1 10
Here is how to read it.
- The outer loop picks the first number of the pair, at index
i. - The inner loop picks the second number, at index
j. It is a loop inside a loop. jstarts ati + 1, so each pair is tried once and no number is paired with itself.checksis a counter we added so that we can measure the cost.- If no pair matches, the function returns −1 for both indexes. Here −1 is a signal that means "not found".
i and j are pointers: each one is an integer that says which cell to look at. They are not doing anything clever yet.
The first output line is for target 13. The pairs are tried in this order: 1 + 3, 1 + 5, 1 + 8, 1 + 11, 3 + 5, 3 + 8, 3 + 11, and then 5 + 8, which is the eighth. The 5 and the 8 are at indexes 2 and 3, so the line says 2 3 8.
The second line is for target 7. No pair adds up to 7, so all ten pairs are checked.
Watch it happen
The inner loop is really a search for one number. If the first number is 1, the second number would have to be 13 − 1 = 12. We call that number its partner. Run the three searches for a partner, and watch the comparisons counter.
- Search for 12The first number is 1, so its partner would be 13 − 1 = 12. Search the whole row for it.
- Search for 10
- Search for 8
- 01
- 13
- 25
- 38
- 411
Run an operation to begin.
Check yourself
The two loops try every pair once. How many pairs is that for 5 numbers, and for 1,000 numbers?
The brute force takes about one second on 10,000 numbers. Roughly how long does it take on 20,000 numbers?
What does this print?
def two_sum_brute(nums, target): checks = 0 for i in range(len(nums)): for j in range(i + 1, len(nums)): # every pair once: j is always after i checks += 1 if nums[i] + nums[j] == target: return i, j, checks return -1, -1, checks
i, j, checks = two_sum_brute([1, 3, 5, 8, 11], 13)print(i, j, checks)i, j, checks = two_sum_brute([1, 3, 5, 8, 11], 7)print(i, j, checks)public class Main { static int[] twoSumBrute(int[] nums, int target) { int checks = 0; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { // every pair once: j is always after i checks++; if (nums[i] + nums[j] == target) return new int[] {i, j, checks}; } } return new int[] {-1, -1, checks}; }
public static void main(String[] args) { int[] hit = twoSumBrute(new int[] {1, 3, 5, 8, 11}, 13); System.out.println(hit[0] + " " + hit[1] + " " + hit[2]); int[] miss = twoSumBrute(new int[] {1, 3, 5, 8, 11}, 7); System.out.println(miss[0] + " " + miss[1] + " " + miss[2]); }}Connect
- Count the pairs that trying every pair must check: n(n − 1) / 2, which is 10 for five numbers and 499,500 for a thousand.
- Say why doubling the numbers gives about four times the work, and call that O(n²).
- Describe the brute force and its cost first, before you improve on it.