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 conditions are met:
nums[i] - nums[j] | == k |
Notice that | val | denotes the absolute value of val . |
i
and j
.nums
and k
?
nums
may contain up to 10^4 elements, and k
could be in the range from 0 to 10^7.k
is negative?
k
is negative, no pair with a negative absolute difference can exist, so the result should be 0.We can solve this problem efficiently using a hash map (unordered_map). The strategy involves the following steps:
k
is negative.k == 0
, count the numbers that appear more than once because the pair (x, x) with |x - x| == 0
is valid.k > 0
, for each unique number num
in the array, check whether num + k
exists in the array using the hash map to ensure O(1) look-up time.Here’s the C++ implementation of the above strategy:
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if (nums.empty() || k < 0) return 0; // No pairs possible for invalid inputs
unordered_map<int, int> numCount;
for (int num : nums) {
numCount[num]++;
}
int result = 0;
for (const auto& entry : numCount) {
int num = entry.first;
if (k == 0) {
// When k == 0, we look for duplicates
if (entry.second > 1) {
result++;
}
} else {
// When k > 0, we look for the pair (num, num + k)
if (numCount.find(num + k) != numCount.end()) {
result++;
}
}
}
return result;
}
};
The time complexity of the solution is (O(n)), where (n) is the number of elements in the array. This is because:
The space complexity is also (O(n)) due to the storage required for the hash map.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?