You are given an array of integers nums and a number k. A k-diff pair is two values taken from two different positions in the array whose difference, in absolute value, is exactly k.
Return how many distinct k-diff pairs there are. Pairs are compared by their values: if the same two values can be picked from several positions, they still count once.
Example 1
Input: nums = [6, 2, 4, 2, 8], k = 2 Output: 3 Why: (2, 4), (4, 6) and (6, 8); the two 2s give (2, 4) only once
2 more examples and the constraints
Example 2
Input: nums = [7, 3, 7, 7, 1], k = 0 Output: 1 Why: only 7 appears more than once, giving (7, 7)
Example 3
Input: nums = [-1, 9, 2, 5], k = 3 Output: 2 Why: (−1, 2) and (2, 5); 9 has no partner
Constraints
- 1 ≤ length of nums ≤ 10,000
- −10,000,000 ≤ nums[i] ≤ 10,000,000
- 0 ≤ k ≤ 10,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n²)
- Sort + two pointersO(n log n)
- Count, then look up x + kO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Check every pair | O(n²) | Mention it, then move on | |
| Sort + two pointers | O(n log n) | Passes; fiddly duplicate skips | |
| Count, then look up x + k | O(n) | Best; simple and linear |
n = length of nums.
Edge cases to test
- k is 0. [7, 3, 7, 7, 1] has one 0-diff pair, (7, 7), no matter how many 7s there are.
- Repeated values with k > 0. Two 2s and one 4 still make just one (2, 4) pair.
- Negative numbers. −1 and 2 differ by 3; work with x + k, never with absolute values of x.
- Single number. One element can never form a pair: the answer is 0.
- k larger than any gap. No partner exists, so the answer is 0.
Common mistakes
- Treating k = 0 like any other k, so every value pairs with itself.
- Counting pairs by position, so duplicates inflate the answer.
- Looking for both x + k and x − k, which counts every pair twice.
How to talk through it
- 1Clarify. Are pairs counted by value or by position? Can k be 0? Can numbers be negative?
- 2Give the brute force. Check every pair and keep a set of (smaller, larger); O(n²) is too slow for 10,000.
- 3Name the lookup. For each distinct x, the only possible partner above it is x + k: one map lookup.
- 4Handle k = 0 apart. Then a pair needs the same value twice, so check the count instead.
- 5Test out loud. Run k = 0 with repeats, a duplicate with k > 0, and negative numbers.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?