#K64242. Count Pairs with Given Difference
Count Pairs with Given Difference
Count Pairs with Given Difference
You are given an array A consisting of n integers and an integer k. Your task is to count the number of unique pairs (i, j) such that the absolute difference between A[i] and A[j] is exactly k, i.e., \(|A[i]-A[j]| = k\).
Note: If k is 0, the answer is defined to be 0. Each valid pair should be counted only once even if it can be found in two different orders.
This problem will test your ability to use efficient data structures to achieve an optimal solution.
inputFormat
The input is read from standard input (stdin) and is formatted as follows:
- The first line contains an integer
T
, the number of test cases. - For each test case, the first line contains two integers
n
andk
, wheren
is the number of elements in the array andk
is the target difference. - The second line of each test case contains
n
space-separated integers representing the elements of the arrayA
.
outputFormat
For each test case, print a single line containing a single integer: the number of unique pairs with an absolute difference equal to k
.
2
5 3
1 5 3 4 2
4 0
1 2 3 4
2
0
</p>