K-diff Pairs in an Array (LeetCode 532): Solution and Explanation
Count the unique pairs of values in an array whose absolute difference is exactly k. Pairs are unique by value, so repeated numbers do not create extra pairs.
Intuition
Because pairs are unique by value, indexes do not matter. What matters is which distinct values exist and, for k = 0, how many times each appears.
For k > 0, every pair has a smaller value x and a larger value x + k. If we always name a pair by its smaller end, each pair is counted exactly once: for every distinct x, just ask whether x + k exists.
When k = 0 the two values are equal, so the pair (x, x) needs x to appear at least twice. A count map answers both questions: membership for k > 0 and frequency for k = 0.
Approach: Count map and one lookup per distinct value
- Count how often each value appears in
nums. - Set
pairs = 0and walk the distinct valuesxof the map. - If
k == 0, add one whencount[x] > 1. - Otherwise, add one when
x + kis a key of the map. - Return
pairs.
Step-by-step example
nums = [3,1,4,1,5], k = 2
- The count map is {3: 1, 1: 2, 4: 1, 5: 1}.
- x = 3: 5 is in the map, so (3, 5) is a pair. pairs = 1.
- x = 1: 3 is in the map, so (1, 3) is a pair. pairs = 2. The second 1 is not checked again.
- x = 4: 6 is missing. x = 5: 7 is missing.
- The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def findPairs(self, nums: List[int], k: int) -> int:
3 count = Counter(nums)
4 pairs = 0
5 for x in count:
6 if k == 0:
7 if count[x] > 1:
8 pairs += 1
9 elif x + k in count:
10 pairs += 1
11 return pairs1class Solution {
2 public int findPairs(int[] nums, int k) {
3 Map<Integer, Integer> count = new HashMap<>();
4 for (int x : nums) count.merge(x, 1, Integer::sum);
5 int pairs = 0;
6 for (int x : count.keySet()) {
7 if (k == 0) {
8 if (count.get(x) > 1) pairs++;
9 } else if (count.containsKey(x + k)) {
10 pairs++;
11 }
12 }
13 return pairs;
14 }
15}1class Solution {
2public:
3 int findPairs(vector<int>& nums, int k) {
4 unordered_map<int, int> count;
5 for (int x : nums) count[x]++;
6 int pairs = 0;
7 for (auto& [x, c] : count) {
8 if (k == 0) {
9 if (c > 1) pairs++;
10 } else if (count.count(x + k)) {
11 pairs++;
12 }
13 }
14 return pairs;
15 }
16};Time and space complexity
O(n)
Building the map is one pass, and each distinct value needs one O(1) average lookup.
O(n)
The map holds at most one entry per distinct value.
Other approaches
Sort and two pointers (time O(n log n), space O(1) besides the sort)
Sort the array, then move two pointers so the difference nums[j] - nums[i] approaches k, skipping duplicate values after each match. Uses no hash map.
Sort and binary search (time O(n log n), space O(1) besides the sort)
Sort, then for each new distinct value binary search for value + k in the part after it.
Common mistakes
- Counting (x, x + k) and (x + k, x) as two pairs. Only check upward from x, never x - k as well.
- Looping over
numsinstead of over distinct values. Duplicates would count the same pair several times. - Treating k = 0 like other k. x + 0 is always in the map, so every value would look like a pair; you need the count to be at least 2.
- Using a plain set for k = 0. A set forgets how many times a value appeared.
Frequently asked questions
Why is the absolute difference handled by checking only x + k?
Any pair with difference k has a smaller end x and a larger end x + k. Checking x + k from every distinct x finds each pair exactly once, from its smaller end.
Can k be negative?
No. The constraints say 0 <= k, and an absolute difference can never be negative anyway.
Is the hash map or the sorted version better?
The map is linear and short to write. The sorted two-pointer version avoids extra memory but needs careful duplicate skipping. Both pass easily for 10^4 numbers.