Adapted from this HackerRank Problem.
Given
N
integers, count the number of pairs of integers whose difference isK
.
- Given the initial
int
array, sort it. - Now iterate through the indices in the array using a lower index (starting at
0
) and an upper index (starting at1
)`. - Calculate the difference between the value at the upper index value and the value at the lower index.
- If the difference is equal to the target difference, increment the count and increment the upper index.
- If the difference is less than the target difference, increment the upper index. A difference less than the target difference implies that the value at the upper index is not large enough.
- If the difference is greater than the target difference, increment the lower index. A difference greater than the target implies that the value at the lower index is not large enough.
- Return the count
public class PairDifferenceCounter {
public static int countPairsWithDifference(int[] values, int difference) {
Arrays.sort(values);
int count = 0;
int lowerIndex = 0;
int upperIndex = 1;
while (upperIndex < values.length) {
int pairDifference = values[upperIndex] - values[lowerIndex];
if (pairDifference == difference) {
count++;
upperIndex++;
} else if (pairDifference > difference) {
lowerIndex++;
} else {
upperIndex++;
}
}
return count;
}
}