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.length
  • i != 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
K-diff Pairs: nums = [3,1,4,1,5], k = 231415|3-1|=2 ✓|5-3|=2 ✓Valid unique pairs: (1,3), (3,5)Output: 2
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
Asked in
Amazon 25 Google 18 Microsoft 12 Facebook 8
67.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen