Skip to content

Instantly share code, notes, and snippets.

@coreyjs
Created August 6, 2020 16:52
Show Gist options
  • Save coreyjs/89111c46c8b29f5fa134f3490ce23bff to your computer and use it in GitHub Desktop.
Save coreyjs/89111c46c8b29f5fa134f3490ce23bff to your computer and use it in GitHub Desktop.
K-diff pairs in an array
from collections import Counter
def find_pairs(nums, k) -> int:
# if k < 0, the result is 0
if k < 0:
return 0
count = Counter(nums)
pairs = set([])
for num in count.keys():
print(num)
if k == 0:
# if k = 0, then we need TWO occurrences of hte same number
if count[num] > 1:
pairs.add((num, num))
else:
otherNum = num + k
if otherNum in count:
pairs.add((num, otherNum) if num <= otherNum else (otherNum, num))
return pairs
num = [3, 1, 2, 7, 5]
k = 2
print(find_pairs(num, k))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment