




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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public int FindPairs(int[] nums, int k) {
6        Dictionary<int, int> map = new Dictionary<int, int>();
7        int count = 0;
8        foreach (var num in nums) {
9            if (map.ContainsKey(num)) map[num]++;
10            else map[num] = 1;
11        }
12        foreach (var kvp in map) {
13            if (k == 0) {
14                if (kvp.Value > 1) count++;
15            } else {
16                if (map.ContainsKey(kvp.Key + k)) count++;
17            }
18        }
19        return count;
20    }
21}C# utilizes a Dictionary for counting the frequency of elements. It then searches for pairs by checking the dictionary keys with the difference considered.
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.
1functionJavaScript's solution first sorts the array, letting two pointers sieve the array for pairs with k differences. With special handling of duplicates, the unique k-diff pairs are effectively derived.