Input: Integer array
Diff: Integer difference
Output: Total number of unique pairs having difference provided in the input.
Here in this problem, the input will be an array of integer and also the difference value. So it will ask to out put either the total unique pairs of elements from the array having the difference or just total count of that pairs.
So, with the use of hash set, it will be achieved in O(n) where n is the total number of elements in an array.
Step to solve this question:
Step 1: Create a Set of all the elements.
Step 2: Iterate over each element in set
Check whether the number (element value + diff) is in HashSet.
Below is the java implementation and sample output.
You can have below code from GIT.
https://github.com/Niravkumar-Patel/SnippetExampleRepo.git
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.HashSet; import java.util.Iterator; public class KDiff { public static void main(String args[]){ int pairCount = 0; Integer elements[] = {1,3,4,5,8,8}; int kDiff = 2; if(elements.length>1 && kDiff>=1 && elements.length == elements.length){ HashSet<Integer> hSet = new HashSet<Integer>(); for(int i=0;i<elements.length;i++){ int inputElement = elements[i]; if(!hSet.contains(inputElement)){ hSet.add(inputElement); } } Iterator<Integer> itSet = hSet.iterator(); while (itSet.hasNext()) { Integer value = itSet.next(); Integer subtractValue = value+kDiff; if(hSet.contains(subtractValue)){ System.out.println("Pair Found:"+value+" & "+subtractValue); pairCount++; } } }else{ pairCount=0; } System.out.println("Total Pairs:"+pairCount); } } |
Sample output of above code:
1 2 3 4 5 6 7 8 |
Input: elements[] = {1,3,4,5,8,8}; int kDiff = 2; Output: Pair Found:1 & 3 Pair Found:3 & 5 Total Pairs:2 |
You can have above code from GIT.