Q2. Pairs with Given DifferenceSolved
Given an one-dimensional integer array A of size N and an integer B.
Count all distinct pairs with difference equal to B.
Here a pair is defined as an integer pair (x, y), where x and y are both numbers in the array and their absolute difference is B.
Problem Constraints
1 <= N <= 104
0 <= A[i], B <= 105
Input Format
First argument is an one-dimensional integer array A of size N.
Second argument is an integer B.
Output Format
Return an integer denoting the count of all distinct pairs with difference equal to B.
Example Input
Input 1:
A = [1, 5, 3, 4, 2]
B = 3
Output 1:
2
Explanation 1:
There are 2 unique pairs with difference 3, the pairs are {1, 4} and {5, 2}
Input 2:
A = [8, 12, 16, 4, 0, 20]
B = 4
Output 2:
5
Explanation 2:
There are 5 unique pairs with difference 4, the pairs are {0, 4}, {4, 8}, {8, 12}, {12, 16} and {16, 20}
Input 3:
A = [1, 1, 1, 2, 2]
B = 0
Output 3:
2
Explanation 3:
There are 2 unique pairs with difference 0, the pairs are {1, 1} and {2, 2}.
From Example 1
3
, for each element in A
, we must have A[i]+3 or A[i]-3
in the arrayelementsSet
that has all distinct elementsFor each element in A
we have a pair of Target elements. So we create two variables to store the values.
targetElement1 = A - B
targetElement2 = currentElement + B
If elementsSet
has targetElement1
, we have successfully found a pair !!
distinctPairs
. It contains all the unique pairs found as stringsdistinctPairs
.Similarly, If elementsSet
has targetElement2
, we have successfully found another pair !!
Add this pair to distinctPairs
.
<aside> 💡 REVERSE the order this time to avoid duplicate entries in the array
</aside>
Return the size of the distinctPairs
set
solve : function(A, B){
let elementsSet = new Set();
let distinctPairs = new Set();
for (let i = 0; i < A.length; i++) {
const currentElement = A[i];
const targetElement1 = currentElement - B;
const targetElement2 = currentElement + B;
if (elementsSet.has(targetElement1)) {
distinctPairs.add([targetElement1, currentElement].toString());
}
if (elementsSet.has(targetElement2)) {
distinctPairs.add([currentElement, targetElement2].toString());
}
elementsSet.add(currentElement);
}
return distinctPairs.size;
}