LeetCode 532: K-diff Pairs in an Array Solution

Master LeetCode problem 532 (K-diff Pairs in an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

532. K-diff Pairs in an Array

Problem Explanation

Explanation

To solve this problem, we can use a hashmap to keep track of the frequency of each number in the array. Then, we can iterate through the hashmap to find the number of unique k-diff pairs based on the given conditions.

  1. Create a hashmap to store the frequency of each number in the array.
  2. Iterate through the hashmap:
    • If k is 0, count the number of elements with frequency greater than 1.
    • If k is not 0, check if the current number + k exists in the hashmap. If it does, increment the count of unique pairs.
  3. Return the count of unique k-diff pairs.

Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(n), to store the hashmap.

Solution Code

class Solution {
    public int findPairs(int[] nums, int k) {
        if (k < 0) {
            return 0;
        }
        
        int count = 0;
        Map<Integer, Integer> freqMap = new HashMap<>();
        
        for (int num : nums) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }
        
        for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
            if (k == 0 && entry.getValue() > 1) {
                count++;
            } else if (k != 0 && freqMap.containsKey(entry.getKey() + k)) {
                count++;
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 532 (K-diff Pairs in an Array)?

This page provides optimized solutions for LeetCode problem 532 (K-diff Pairs in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 532 (K-diff Pairs in an Array)?

The time complexity for LeetCode 532 (K-diff Pairs in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 532 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 532 in Java, C++, or Python.

Back to LeetCode Solutions