Given an array of integers and an integer k
, you need to find the number of unique k-diff
pairs in the array. Here, a k-diff
pair is defined as an integer pair (i, j)
, where i
and j
are indices in the array, such that |nums[i] - nums[j]| = k
and i != j
.
Note:
(i, j)
and (j, i)
are considered the same, thus should only be counted once.Input: nums = [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Input: nums = [1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4), and (4, 5).
Input: nums = [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
k
?
k
are between -10^7 to 10^7.k
is zero, we are looking for duplicates in the array.|nums[i] - nums[j]| = k
.import java.util.*;
public class KDiffPairs {
public int findPairs(int[] nums, int k) {
if (k < 0) return 0; // Since absolute difference cannot be negative
Set<Integer> set = new HashSet<>();
Set<Integer> seenPairs = new HashSet<>();
for (int num : nums) {
if (set.contains(num + k)) {
seenPairs.add(num);
}
if (set.contains(num - k)) {
seenPairs.add(num - k);
}
set.add(num);
}
return seenPairs.size();
}
public static void main(String[] args) {
KDiffPairs solution = new KDiffPairs();
int[] nums1 = {3, 1, 4, 1, 5};
int k1 = 2;
System.out.println(solution.findPairs(nums1, k1)); // Output: 2
int[] nums2 = {1, 2, 3, 4, 5};
int k2 = 1;
System.out.println(solution.findPairs(nums2, k2)); // Output: 4
int[] nums3 = {1, 3, 1, 5, 4};
int k3 = 0;
System.out.println(solution.findPairs(nums3, k3)); // Output: 1
}
}
n
is the number of elements in the array since we only traverse the array once and the HashSet operations (insert, search) are average O(1).Feel free to ask more clarifying questions or provide feedback on this strategy!
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?