A simple but inefficient solution involves performing a linear search for each element e1 to find e2 = e1 + k in the rest of the array, resulting in an O(n^2) time complexity. However, we can improve upon this.
publicclassSolution {
publicintcountKDifference(int[] nums, int k) {
HashMap<Integer, Integer> freqMap =new HashMap<>();
int count = 0;
for (int num : nums) {
if (freqMap.containsKey(num + k)) {
count += freqMap.get(num + k);
}
if (freqMap.containsKey(num - k)) {
count += freqMap.get(num - k);
}
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
defcountKDifference(nums, k):
freq_map = {}
count =0for num in nums:
if num + k in freq_map:
count += freq_map[num + k]
if num - k in freq_map:
count += freq_map[num - k]
if num in freq_map:
freq_map[num] +=1else:
freq_map[num] =1return count
Time: O(n), where (n) is the number of elements in the array nums, since we are iterating through the array and using a HashMap for constant time get and put operations.
Space: O(n) as we are storing elements in a HashMap.
publicclassSolution {
publicintcountKDifference(finalint[] A, finalint K) {
final HashSet<Integer> hs =new HashSet<>();
int count = 0;
for (int i = 0; i < A.length; i++) {
if (hs.contains(A[i]- K)) {
count++;
}
if (hs.contains(A[i]+ K)) {
count++;
}
hs.add(A[i]);
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
defcountKDifference(nums, k):
seen = set()
count =0for num in nums:
if (num - k) in seen:
count +=1if (num + k) in seen:
count +=1 seen.add(num)
return count
If space is limited, an alternative solution uses O(1) space and O(n log k) time. Instead of a linear search for e2 = e1 + k, we employ an optimal binary search.
Sort the array, which takes O(n log n) time.
For each element e1 in the sorted array, search for an element e2 > e1 such that A[e2] - A[e1] = k.
By performing a binary search for e2 from e1 + 1 to e1 + diff in the sorted array, we limit our search to O(log k) time for each element. The overall time complexity becomes O(n log n) + O(n log k). If k > n, the time complexity of this algorithm is O(n log k) with O(1) space.
For finding pairs with the minimum difference, you can refer to the solution in Min difference pairs.