K-diff Pairs in an Array

Problem Id: 532 Difficulty: Medium


Intuition

Solution


class Solution:
    def findPairs(self, nums: List[int], k: int) -> int:
        ans = 0
        if k == 0:
            count = {}
            for num in nums:
                if num not in count:
                    count[num] = 0
                count[num] += 1
            for k in count:
                if count[k] > 1:
                    ans += 1
            return ans
        elif k < 0:
            return 0
        nums = set(nums)
        for num in nums:
            if num + k in nums:
                ans += 1
            if num - k in nums:
                ans += 1
        return ans // 2