#532
Medium Algorithms K diff pairs in an array
Array Hash Table Two Pointers Binary Search Sorting
45.6% acceptance
Feb 19, 2026
4144
2289
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.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn find_pairs(nums: Vec<i32>, k: i32) -> i32 {
if k < 0 { return 0; }
let mut map: HashMap<i32, i32> = HashMap::new();
for &n in &nums { *map.entry(n).or_insert(0) += 1; }
let mut count = 0i32;
for (&key, &val) in &map {
if k == 0 {
if val >= 2 { count += 1; }
} else {
if map.contains_key(&(key + k)) { count += 1; }
}
}
count
}
}