Pairs that are k apart
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
Problem
Write a function that takes a list of numbers and a number k, and returns how many pairs in the list have exactly that difference.
With 1, 5, 3, 4 and 2, and k equal to 3, the answer is 2: the 1 with the 4, and the 5 with the 2.
The rules: the difference is never negative, so measure the distance between the two, not which one comes first. Each pair counts only once, because the 1 with the 4 and the 4 with the 1 are the same pair. A number never pairs with itself, but if the same value shows up twice those are two different numbers: in 2, 4, 1, 3 and 4, with k equal to 2, there are three pairs, because the 2 goes with both 4s. If k is 0, the pairs are the numbers that are equal. With fewer than two numbers there is nothing to compare: you return 0.
Compare each number with the ones you have already seen. And if you sort the list first, you can stop looking as soon as the difference goes past k.
Examples
A difference of 3
[1, 5, 3, 4, 2], 3 → 2
Four apart
[8, 12, 16, 4, 0, 20], 4 → 5
A repeated value
[2, 4, 1, 3, 4], 2 → 3
No pairs at all
[10, 20, 30], 5 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def count_pairs(values, k):
passJavaScript
function countPairs(values, k) {
}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.