K-diff Pairs in an Array

medium array hash map

Problem

Return the number of unique k-diff pairs (i, j) where |nums[i] − nums[j]| == k. Pairs are unique by value; k ≥ 0.

Inputnums = [3, 1, 4, 1, 5], k = 2
Output2
Pairs: (1, 3) and (3, 5).

from collections import Counter

def find_pairs(nums, k):
    cnt = Counter(nums)
    if k == 0:
        return sum(1 for v in cnt.values() if v >= 2)
    return sum(1 for x in cnt if x + k in cnt)
function findPairs(nums, k) {
  const cnt = new Map();
  for (const x of nums) cnt.set(x, (cnt.get(x) || 0) + 1);
  let pairs = 0;
  if (k === 0) {
    for (const v of cnt.values()) if (v >= 2) pairs++;
  } else {
    for (const x of cnt.keys()) if (cnt.has(x + k)) pairs++;
  }
  return pairs;
}
class Solution {
    public int findPairs(int[] nums, int k) {
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int x : nums) cnt.merge(x, 1, Integer::sum);
        int pairs = 0;
        if (k == 0) {
            for (int v : cnt.values()) if (v >= 2) pairs++;
        } else {
            for (int x : cnt.keySet()) if (cnt.containsKey(x + k)) pairs++;
        }
        return pairs;
    }
}
int findPairs(vector<int>& nums, int k) {
    unordered_map<int, int> cnt;
    for (int x : nums) cnt[x]++;
    int pairs = 0;
    if (k == 0) {
        for (auto& [v, c] : cnt) if (c >= 2) pairs++;
    } else {
        for (auto& [v, c] : cnt) if (cnt.count(v + k)) pairs++;
    }
    return pairs;
}
Time: O(n) Space: O(n)