K-diff Pairs in an Array - Problem
You're given an array of integers nums and an integer k. Your task is to find the number of unique k-diff pairs in the array.
A k-diff pair is defined as a pair of integers (nums[i], nums[j]) where:
0 <= i, j < nums.lengthi != j(different indices)|nums[i] - nums[j]| == k(absolute difference equals k)
Important: We only count unique pairs - if the same pair of values appears multiple times in the array, it should only be counted once.
Example: In array [3, 1, 4, 1, 5] with k = 2, the pairs (1,3) and (3,5) both have an absolute difference of 2, so the answer is 2.
Input & Output
example_1.py โ Basic case with positive k
$
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 count unique pairs, so even though 1 appears twice, we only count the pair (1,3) once.
example_2.py โ Case with duplicates and k=0
$
Input:
nums = [1,2,3,4,5], k = 1
โบ
Output:
4
๐ก Note:
There are four 1-diff pairs: (1,2), (2,3), (3,4), and (4,5). Each consecutive pair has a difference of 1.
example_3.py โ Edge case with k=0
$
Input:
nums = [1,3,1,5,4], k = 0
โบ
Output:
1
๐ก Note:
When k=0, we're looking for pairs with the same value. Only the number 1 appears more than once, so there's exactly 1 unique pair: (1,1).
Time & Space Complexity
Time Complexity
O(n)
One pass to build frequency map O(n) + one pass through unique elements O(n)
โ Linear Growth
Space Complexity
O(n)
Hash table to store frequency of all unique elements
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 104
- -107 โค nums[i] โค 107
- 0 โค k โค 107
- Follow-up: Can you solve this in O(n) time complexity?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code