Skip to content
JZLeetCode
Go back

LeetCode 532 LintCode 1187 K-diff Pairs in An Array

Table of contents

Open Table of contents

Description

Question Links: LeetCode 532, LintCode 1187

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:

Notice that |val| denotes the absolute value of val.

Example 1:

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).
Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

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).

Example 3:

Input: nums = [1,3,1,5,4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Constraints:

Idea

We could count the values in the array and then iterate through the counter.

  1. If k==0, we count if this element count is >= 2. Because we would only consider the unique pairs, if the count is <= 1, there is no such pair; if the count is >= 2, we count the one pair of v and v.
  2. If k>0, we look for v+k in the counter.

Complexity: Time O(n)O(n), Space O(n)O(n).

C++

// leet 532, 3 ms, 17.22 mb
class Solution {
public:
    int findPairs(vector<int> &nums, int k) {
        int res = 0;
        unordered_map<int, int> cnt;
        for (auto &n: nums) cnt[n] += 1;
        for (auto e: cnt) res += k > 0 && cnt.count(e.first + k) || k == 0 && e.second > 1;
        return res;
    }
};

Java

// leet 532
public static int findPairs(int[] nums, int k) {
    Map<Integer, Integer> cnt = new HashMap<>();
    for (int n : nums) cnt.merge(n, 1, Integer::sum);
    int res = 0;
    for (var e : cnt.entrySet()) {
        if (k > 0 && cnt.containsKey(e.getKey() + k)) res++;
        else if (k == 0 && e.getValue() > 1) res++;
    }
    return res;
}

Python

class Solution:
    """5 ms, 19 mb"""

    def findPairs(self, nums: list[int], k: int) -> int:
        cnt = Counter(nums)
        return sum([k > 0 and c + k in cnt or k == 0 and cnt[c] > 1 for c in cnt])

Rust

use std::collections::HashMap;

/// leet 532, 0 ms, 2.3 mb
impl Solution {
    pub fn find_pairs(nums: Vec<i32>, k: i32) -> i32 {
        let mut cnt: HashMap<i32, i32> = HashMap::new();
        for &n in &nums { *cnt.entry(n).or_insert(0) += 1; }
        let mut res = 0;
        for (&key, &val) in &cnt {
            if k > 0 && cnt.contains_key(&(key + k)) { res += 1; }
            else if k == 0 && val > 1 { res += 1; }
        }
        res
    }
}
Share this post on:

Previous Post
LeetCode 2017 Grid Game
Next Post
LeetCode Meeting Rooms Derivative Question