Leetcode 2006. 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 < j
such that |nums[i] - nums[j]| == k
.
nums
?k
?Let’s consider an example to clarify:
Input: nums = [1, 2, 2, 1], k = 1
Output: 4
Explanation: The pairs with absolute difference 1 are:
- (0, 1) -> 1 - 2 = -1 (abs: 1)
- (1, 2) -> 2 - 2 = 0 (not counted)
- (0, 3) -> 1 - 1 = 0 (not counted)
- (1, 3) -> 2 - 1 = 1
- (2, 3) -> 2 - 1 = 1
We will use a HashMap to keep track of the frequency of the numbers we’ve encountered so far. This will allow us to efficiently find the number of pairs with the desired absolute difference.
k
.import java.util.HashMap;
public class NumberOfPairsWithDifference {
public int countKDifference(int[] nums, int k) {
HashMap<Integer, Integer> countMap = new HashMap<>();
int count = 0;
for (int num : nums) {
// Check pairs where difference is `k`
if (countMap.containsKey(num - k)) {
count += countMap.get(num - k);
}
if (countMap.containsKey(num + k)) {
count += countMap.get(num + k);
}
// Update the map with the current number
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
return count;
}
public static void main(String[] args) {
NumberOfPairsWithDifference solution = new NumberOfPairsWithDifference();
int[] nums = {1, 2, 2, 1};
int k = 1;
int result = solution.countKDifference(nums, k);
// Expected output is 4
System.out.println("Number of pairs: " + result);
}
}
O(n)
, where n
is the length of the input array nums
.O(n)
due to the additional HashMap that potentially stores every element of the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?