Count Pairs with Absolute Difference K
Problem statement
You are given an integer array nums and a non-negative integer k. Return the number of index pairs (i, j) with i < j such that |nums[i] - nums[j]| == k.
Each pair of indices is counted once. Equal values at different indices form different pairs.
Function
countPairsWithDifference(nums: int[], k: int) → longExamples
Example 1
nums = [1,5,3,4,2]k = 2return = 3The pairs with difference 2 are (1, 3), (5, 3), and (4, 2), at indices (0, 2), (1, 2), and (3, 4). The answer is 3.
Example 2
nums = [3,1,3,3]k = 0return = 3With k = 0 we count pairs of equal values. The three 3s at indices 0, 2, and 3 form 3 pairs.
Example 3
nums = [-2,2,-2]k = 4return = 2Index 1 holds 2, and both -2s differ from it by 4. That gives the pairs (0, 1) and (1, 2), so the answer is 2.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^90 <= k <= 10^9