K-diff Pairs in an Array - Problem
Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j]) where the following are true:
0 <= i, j < nums.lengthi != j|nums[i] - nums[j]| == k
Notice that |val| denotes the absolute value of val.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,1,4,1,5], k = 2
›
Output:
2
💡 Note:
There are two 2-diff pairs: (1,3) and (3,5). Note that we only count unique pairs, so (1,3) from different positions counts as one pair.
Example 2 — No Valid Pairs
$
Input:
nums = [1,2,3,4,5], k = 1
›
Output:
4
💡 Note:
Valid pairs are (1,2), (2,3), (3,4), and (4,5). Each consecutive pair has difference 1.
Example 3 — Duplicate Elements
$
Input:
nums = [1,3,1,5,4], k = 0
›
Output:
1
💡 Note:
For k=0, we need identical pairs. Only the number 1 appears more than once, giving us one unique pair (1,1).
Constraints
- 1 ≤ nums.length ≤ 104
- -107 ≤ nums[i] ≤ 107
- 0 ≤ k ≤ 107
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of integers and target difference k
2
Process
Find all pairs where |a - b| = k
3
Output
Count of unique k-diff pairs
Key Takeaway
🎯 Key Insight: Use hash map or sorting to avoid O(n²) brute force comparison
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code