LeetCode 2006: Count Number of Pairs With Absolute Difference K Solution
Master LeetCode problem 2006 (Count Number of Pairs With Absolute Difference K), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2006. Count Number of Pairs With Absolute Difference K
Problem Explanation
Explanation
To solve this problem, we can iterate through the array and for each element nums[i], we check if there exists any element nums[j] such that |nums[i] - nums[j]| == k. We can achieve this by maintaining a count of the occurrences of each number in a HashMap.
- Initialize a HashMap to store the count of each number in the input array.
- Iterate through the array and for each element:
- Check if
nums[i] - kornums[i] + kexists in the HashMap. If either exists, increment the count by the value in the HashMap. - Update the count of
nums[i]in the HashMap.
- Check if
- Return the total count of pairs found.
The time complexity of this approach is O(n) where n is the size of the input array nums. The space complexity is also O(n) to store the count of each number in the HashMap.
Solution Code
import java.util.HashMap;
class Solution {
public int countKDifference(int[] nums, int k) {
HashMap<Integer, Integer> countMap = new HashMap<>();
int pairsCount = 0;
for (int num : nums) {
pairsCount += countMap.getOrDefault(num - k, 0);
pairsCount += countMap.getOrDefault(num + k, 0);
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
return pairsCount;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2006 (Count Number of Pairs With Absolute Difference K)?
This page provides optimized solutions for LeetCode problem 2006 (Count Number of Pairs With Absolute Difference K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2006 (Count Number of Pairs With Absolute Difference K)?
The time complexity for LeetCode 2006 (Count Number of Pairs With Absolute Difference K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2006 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2006 in Java, C++, or Python.