




Sponsored
Sponsored
This approach uses a HashMap to track the frequency of each element in the array. For each unique element, we will check if there's another element that can form a k-diff pair with it. When k is zero, we need to check if there are duplicates present in the list.
Time Complexity: O(n) because we iterate over the array and then over the hashmap that is bounded by a constant size. Space Complexity: O(n) to store the frequency map.
1function findPairs(nums, k) {
2    let map = new Map();
3    let count = 0;
4    for (let num of nums) {
5        map.set(num, (map.get(num) || 0) + 1);
6    }
7    for (let [key, val] of map) {
8        if (k == 0) {
9            if (val > 1) count++;
10        } else if (map.has(key + k)) {
11            count++;
12        }
13    }
14    return count;
15}This JavaScript solution uses a Map to keep a count of array elements, transitioning through the map entries to establish k-diff pairs, with special handling for k=0.
This approach involves sorting the array initially, then using two pointers to determine unique k-diff pairs. The array being sorted helps us efficiently reduce potential pair checks, and ensure pairs are considered only once.
Time Complexity: O(n log n) due to sorting. Space Complexity: O(1) if disregard input.
1#include <vector>
#include <algorithm>
int findPairs(std::vector<int>& nums, int k) {
    std::sort(nums.begin(), nums.end());
    int count = 0, left = 0, right = 0;
    while (right < nums.size()) {
        if (right == left || nums[right] - nums[left] < k) {
            ++right;
        } else if (nums[right] - nums[left] > k) {
            ++left;
        } else { // nums[right] - nums[left] == k
            ++count;
            ++left;
            while (right < nums.size() && nums[right] == nums[right - 1]) {
                ++right;
            }
        }
    }
    return count;
}The array is sorted initially, after which two pointers determine the valid pairs by comparing the difference to k. If a valid pair is found, the left pointer moves forward. Duplicate elements are effectively managed.