#117 · Dictionaries and sets · Advanced · 110 XP · about 18 min
Write count_k_diff_pairs(nums, k) that counts the different pairs of values (a, b) in nums with b - a == k, where a and b come from two different positions in the list.
Pairs are counted by their values, not their positions: (1, 3) counts once, however many 1s and 3s there are. k is never negative, and when k is 0 a pair needs a value that appears at least twice.
count_k_diff_pairs([3, 1, 4, 1, 5], 2) # returns 2 count_k_diff_pairs([1, 2, 3, 4, 5], 1) # returns 4 count_k_diff_pairs([1, 3, 1, 5, 4], 0) # returns 1
In the first example the pairs are (1, 3) and (3, 5); the second 1 does not make a new pair.
0 <= len(nums) <= 100,000-10**7 and 10**70 <= k <= 10**7Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.