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.
1 <= nums.length <= 2001 <= nums[i] <= 1000 <= k <= 100k?
k is guaranteed to be non-negative.0 if no such pairs are found.(i, j) with i < j.|nums[i] - nums[j]| is equal to k.num, check if (num + k) or (num - k) exists in the hashmap.k.Here’s the implementation using the optimized approach:
def countKDifference(nums, k):
from collections import defaultdict
freq_map = defaultdict(int)
count = 0
for num in nums:
# Check for pairs with (num + k)
count += freq_map[num + k]
# Check for pairs with (num - k)
count += freq_map[num - k]
# Update the frequency map
freq_map[num] += 1
return count
# Example usage
nums = [1, 2, 2, 1]
k = 1
print(countKDifference(nums, k)) # Output: 4
n is the length of the input array nums.This efficient approach ensures that we only pass through the list a constant number of times and check for conditions in constant time, making it very suitable given the problem constraints.
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?