K-diff Pairs in an Array (LeetCode 532): Solution and Explanation

Medium
Array
Hash Table
Two Pointers
Binary Search
Sorting

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

  1. Count how often each value appears in nums.
  2. Set pairs = 0 and walk the distinct values x of the map.
  3. If k == 0, add one when count[x] > 1.
  4. Otherwise, add one when x + k is a key of the map.
  5. Return pairs.

Step-by-step example

nums = [3,1,4,1,5], k = 2
  1. The count map is {3: 1, 1: 2, 4: 1, 5: 1}.
  2. x = 3: 5 is in the map, so (3, 5) is a pair. pairs = 1.
  3. x = 1: 3 is in the map, so (1, 3) is a pair. pairs = 2. The second 1 is not checked again.
  4. x = 4: 6 is missing. x = 5: 7 is missing.
  5. 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 pairs
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Count map and one lookup per distinct value O(n)
Sort and two pointers O(n log n)
Sort and binary search O(n log n)
Time

O(n)

Building the map is one pass, and each distinct value needs one O(1) average lookup.

Space

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 nums instead 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.