Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

532. K-diff Pairs in an Array

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.