2116. Count Number of Pairs With Absolute Difference K
My accepted Python solution to LeetCode problem 2116, Count Number of Pairs With Absolute Difference K, running in 4ms.
- Difficulty: Easy
- Python
- Runtime 4ms
- Memory 17.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 4ms, memory 17.1MB, accepted 2025-12-29.
class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
# Use hash map to count: for each num, look for num-k and num+k
# Time: O(n), Space: O(n)
from collections import Counter
count = Counter(nums)
result = 0
for num in count:
if num + k in count:
result += count[num] * count[num + k]
return result