2025-08-16 11:04:12 +0000 UTC

Count Number of Pairs With Absolute Difference K

Code

class Solution:
    def countKDifference(self, nums: List[int], k: int) -> int:
        freqs = [0] * 102
        count = 0
        for num in nums:
            freqs[num] += 1
        for num in nums:
            freqs[num] = max(freqs[num] - 1, 0)
            target = num + k
            for target in (num - k, num + k):
                if target >= 0 and target < 102 and freqs[target] > 0:
                    count += freqs[target]
        return count