KatInterview

532. K-diff Pairs in an Array

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to find the number of unique pairs of integers in an array nums whose absolute difference is exactly k. A pair is defined by its values, not its indices. For instance, if nums = [1, 3, 1, 5] and k = 2, the pair (1, 3) is counted only once, even though 1 appears twice.

Solution

K-diff Pairs in an Array in Python

from collections import Counter

class Solution:
    def findPairs(self, nums: list[int], k: int) -> int:
        # The absolute difference cannot be negative.
        if k < 0:
            return 0
        
        # Use a Counter to get the frequency of each number.
        counts = Counter(nums)
        pair_count = 0
        
        # Case 1: k = 0
        # We are looking for pairs (x, x), which means we need to find numbers
        # that appear more than once.
        if k == 0:
            for count in counts.values():
                if count > 1:
                    pair_count += 1
        # Case 2: k > 0
        # We are looking for pairs (x, y) where y = x + k.
        else:
            for num in counts:
                # Check if a number `num + k` exists in our counter.
                # Iterating through the keys ensures we count each pair only once.
                # For example, if we have (1, 3), we find it when processing 1.
                # We don't need to check for num - k when processing 3, as that would be the same pair.
                if num + k in counts:
                    pair_count += 1
                    
        return pair_count

K-diff Pairs in an Array in Java

class Solution {
    public int findPairs(int[] nums, int k) {
        // The absolute difference cannot be negative.
        if (k < 0) {
            return 0;
        }

        // Use a hash map to count the frequency of each number.
        Map<Integer, Integer> counts = new HashMap<>();
        for (int num : nums) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
        }

        int pairCount = 0;
        // Case 1: k = 0
        // We are looking for pairs (x, x), which means we need to find numbers
        // that appear more than once.
        if (k == 0) {
            for (int count : counts.values()) {
                if (count > 1) {
                    pairCount++;
                }
            }
        } 
        // Case 2: k > 0
        // We are looking for pairs (x, y) where y = x + k.
        else {
            for (int num : counts.keySet()) {
                // Check if a number `num + k` exists in our map.
                // Iterating through the keys ensures we count each pair only once.
                // For example, if we have (1, 3), we find it when processing 1.
                // We don't need to check for num - k when processing 3, as that would be the same pair.
                if (counts.containsKey(num + k)) {
                    pairCount++;
                }
            }
        }

        return pairCount;
    }
}

K-diff Pairs in an Array in C++

class Solution {
public:
    int findPairs(vector<int>& nums, int k) {
        // The absolute difference cannot be negative.
        if (k < 0) {
            return 0;
        }

        // Use a hash map to count the frequency of each number.
        unordered_map<int, int> counts;
        for (int num : nums) {
            counts[num]++;
        }

        int pair_count = 0;
        // Case 1: k = 0
        // We are looking for pairs (x, x), which means we need to find numbers
        // that appear more than once.
        if (k == 0) {
            for (auto const& [num, count] : counts) {
                if (count > 1) {
                    pair_count++;
                }
            }
        } 
        // Case 2: k > 0
        // We are looking for pairs (x, y) where y = x + k.
        else {
            for (auto const& [num, count] : counts) {
                // Check if a number `num + k` exists in our map.
                // Iterating through the keys ensures we count each pair only once.
                // For example, if we have (1, 3), we find it when processing 1.
                // We don't need to check for num - k when processing 3, as that would be the same pair.
                if (counts.count(num + k)) {
                    pair_count++;
                }
            }
        }

        return pair_count;
    }
};

K-diff Pairs in an Array in TypeScript

function findPairs(nums: number[], k: number): number {
    // The absolute difference cannot be negative.
    if (k < 0) {
        return 0;
    }

    // Use a Map to count the frequency of each number.
    const counts = new Map<number, number>();
    for (const num of nums) {
        counts.set(num, (counts.get(num) || 0) + 1);
    }

    let pairCount = 0;
    // Case 1: k = 0
    // We are looking for pairs (x, x), which means we need to find numbers
    // that appear more than once.
    if (k === 0) {
        for (const count of counts.values()) {
            if (count > 1) {
                pairCount++;
            }
        }
    } 
    // Case 2: k > 0
    // We are looking for pairs (x, y) where y = x + k.
    else {
        for (const num of counts.keys()) {
            // Check if a number `num + k` exists in our map.
            // Iterating through the keys ensures we count each pair only once.
            // For example, if we have (1, 3), we find it when processing 1.
            // We don't need to check for num - k when processing 3, as that would be the same pair.
            if (counts.has(num + k)) {
                pairCount++;
            }
        }
    }

    return pairCount;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.