K-diff Pairs in an Array (Leetcode 532)
Problem Link: https://leetcode.com/problems/k-diff-pairs-in-an-array/
class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
d={}
for i in nums:
if(i not in d):
d[i]=1
else:
d[i]+=1
ans=0
# Here, we are traversing the dictionary, bcoz
# we need unique pairs
for i in d:
# If k==0, a unique pair exists if the ele
# occurs more than 1 time.
if(k==0 and d[i]>1):
ans+=1
elif(k>0 and k+i in d):
ans+=1
return ans
Last updated