2006. Count Number of Pairs With Absolute Difference K LeetCode Solution
In this guide, you will get 2006. Count Number of Pairs With Absolute Difference K LeetCode Solution with the best time and space complexity. The solution to Count Number of Pairs With Absolute Difference K problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Number of Pairs With Absolute Difference K solution in C++
- Count Number of Pairs With Absolute Difference K solution in Java
- Count Number of Pairs With Absolute Difference K solution in Python
- Additional Resources

Problem Statement of Count Number of Pairs With Absolute Difference K
Given an integer array nums and an integer k, return the number of pairs (i, j) where i = 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
– [1,2,2,1]
– [1,2,2,1]
– [1,2,2,1]
– [1,2,2,1]
Example 2:
Input: nums = [1,3], k = 3
Output: 0
Explanation: There are no pairs with an absolute difference of 3.
Example 3:
Input: nums = [3,2,1,5,4], k = 2
Output: 3
Explanation: The pairs with an absolute difference of 2 are:
– [3,2,1,5,4]
– [3,2,1,5,4]
– [3,2,1,5,4]
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 100
1 <= k <= 99
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(100) = O(1)
2006. Count Number of Pairs With Absolute Difference K LeetCode Solution in C++
class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
constexpr int kMax = 100;
int ans = 0;
vector<int> count(kMax + 1);
for (const int num : nums)
++count[num];
for (int i = k + 1; i <= kMax; ++i)
ans += count[i] * count[i - k];
return ans;
}
};
/* code provided by PROGIEZ */
2006. Count Number of Pairs With Absolute Difference K LeetCode Solution in Java
class Solution {
public int countKDifference(int[] nums, int k) {
final int kMax = 100;
int ans = 0;
int[] count = new int[kMax + 1];
for (final int num : nums)
++count[num];
for (int i = k + 1; i <= kMax; ++i)
ans += count[i] * count[i - k];
return ans;
}
}
// code provided by PROGIEZ
2006. Count Number of Pairs With Absolute Difference K LeetCode Solution in Python
class Solution:
def countKDifference(self, nums: list[int], k: int) -> int:
count = collections.Counter(nums)
return sum(count[i] * count[i - k] for i in range(k + 1, 101))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.