|
| 1 | +/* |
| 2 | +You are given with an array of integers and an integer K. You have to find and print the count of all such pairs which have difference K. |
| 3 | +Note: Take absolute difference between the elements of the array. |
| 4 | + |
| 5 | +Input Format: |
| 6 | +The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol n. |
| 7 | +The following line contains n space separated integers, that denote the value of the elements of the array. |
| 8 | +The following line contains an integer, that denotes the value of K. |
| 9 | + |
| 10 | +Output format : |
| 11 | +The first and only line of output contains count of all such pairs which have an absolute difference of K. |
| 12 | + |
| 13 | +Constraints : |
| 14 | +0 <= n <= 10^4 |
| 15 | +Time Limit: 1 sec |
| 16 | + |
| 17 | +Sample Input 1 : |
| 18 | +4 |
| 19 | +5 1 2 4 |
| 20 | +3 |
| 21 | +Sample Output 1 : |
| 22 | +2 |
| 23 | + |
| 24 | +Sample Input 2 : |
| 25 | +4 |
| 26 | +4 4 4 4 |
| 27 | +0 |
| 28 | +Sample Output 2 : |
| 29 | +6 |
| 30 | +*/ |
| 31 | +import java.util.HashMap; |
| 32 | +public class Solution { |
| 33 | + |
| 34 | + public static int getPairsWithDifferenceK(int arr[], int k) { |
| 35 | + //Write your code here |
| 36 | + HashMap<Integer,Integer> map = new HashMap<>(); |
| 37 | + for(int key:arr) |
| 38 | + { |
| 39 | + if(map.containsKey(key)) |
| 40 | + { |
| 41 | + map.put(key,map.get(key)+1); |
| 42 | + } |
| 43 | + else |
| 44 | + { |
| 45 | + map.put(key,1); |
| 46 | + } |
| 47 | + } |
| 48 | + /* |
| 49 | + for (Integer i: map.keySet()) |
| 50 | + { |
| 51 | + System.out.println(i + ": " + map.get(i)); |
| 52 | + } |
| 53 | + System.out.println(); |
| 54 | + */ |
| 55 | + int countPairs=0; |
| 56 | + if (k==0) |
| 57 | + { |
| 58 | + for (Integer i: map.keySet()) |
| 59 | + { |
| 60 | + int val=map.get(i); |
| 61 | + countPairs=countPairs+(val*(val-1))/2; |
| 62 | + } |
| 63 | + return countPairs; |
| 64 | + } |
| 65 | + |
| 66 | + for (Integer i: map.keySet()) |
| 67 | + { |
| 68 | + //System.out.println("Current element: "+i); |
| 69 | + //System.out.println("Need to find: "+(i-k)+", "+(i+k)); |
| 70 | + if (map.containsKey(k+i)) |
| 71 | + { |
| 72 | + //System.out.println("Found " + (k+i)); |
| 73 | + countPairs=countPairs+(map.get(i)*map.get(k+i)); |
| 74 | + //System.out.println("Current count of pairs: "+countPairs); |
| 75 | + } |
| 76 | + if (map.containsKey(i-k)) |
| 77 | + { |
| 78 | + //System.out.println("Found " + (i-k)); |
| 79 | + countPairs=countPairs+(map.get(i)*map.get(i-k)); |
| 80 | + //System.out.println("Current count of pairs: "+countPairs); |
| 81 | + } |
| 82 | + //System.out.println(); |
| 83 | + } |
| 84 | + countPairs=countPairs/2; |
| 85 | + return countPairs; |
| 86 | + } |
| 87 | +} |
0 commit comments