[
array
sort
two pointers
counter
]
Leetcode 0532. K-diff Pairs in an Array
https://leetcode.com/problems/k-diff-pairs-in-an-array
Let us just use counter and count frequency of each number in our array. We can have two options:
k > 0
, it means, that for each unique numberi
we are asking if numberi+k
also in table.k = 0
, it means, that we are looking for pairs of equal numbers, so just check each frequency.
Complexity: time and space complexity is O(n)
, because we traverse our array twice: first time to create counter and second to find res
.
class Solution:
def findPairs(self, nums, k):
count = Counter(nums)
if k > 0:
res = sum([i + k in count for i in count])
else:
res = sum([count[i] > 1 for i in count])
return res
If you like the solution, you can upvote it on leetcode discussion section: Problem 0532