Pairs that add up
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
Problem
Write a function that takes a list of numbers and a goal, and returns how many pairs in the list add up to that goal.
With 2, 6, 4, 8 and 4 and the goal 10 the answer is 3: the 2 with the 8, and the 6 with each of the two 4s.
The rules: a pair is two numbers at different positions, so no number teams up with itself; and the 2 with the 8 is the same pair as the 8 with the 2, so it counts only once.
Watch out for repeats, because pairs are counted by position and not by value: in a list of four 1s with the goal 2 there are 6 pairs, even though every one of them adds the same numbers.
If there is no pair at all, or the list has fewer than two numbers, the answer is 0.
It is enough to compare each number with the ones that come after it: the ones behind already compared themselves with you.
Examples
The example
[2, 6, 4, 8, 4], 10 → 3
With a negative number
[1, 5, 7, -1, 5], 6 → 3
No pair at all
[2, 3, 9], 20 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def total_pairs(items, goal):
passJavaScript
function totalPairs(items, goal) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.