Problem Description
Given an integer array and an integer k, find the number of unique k-diff pairs in the array. A k-diff pair is defined as a pair of numbers (nums[i], nums[j]) such that:
- 0 <= i, j < nums.length and i != j
- The absolute difference between the pair equals k. Note that for a pair (a, b), the order does not matter and you should count each unique pair only once.
Key Insights
- For k < 0, the answer is always 0 because the absolute difference cannot be negative.
- When k is 0, you are looking for numbers that appear at least twice.
- For k > 0, it is efficient to use a hash set or a hash map to check if each number's complement (number + k) exists.
- Uniqueness is ensured by processing each number only once from the set of unique numbers.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array since we iterate over the array and then over the unique numbers. Space Complexity: O(n), for storing the frequency count or the unique elements in a hash map or hash set.
Solution
The solution first checks if k is negative, returning 0 immediately if true. For k equals 0, we count numbers that appear more than once using a frequency map. For k greater than 0, a set of unique numbers is created and for each number, we check if (number + k) is also present in the set. Each valid case contributes to the result count, ensuring that only unique pairs are considered.