# K-Difference

**Problem Statement**

In this challenge, you will be given an array of integers, each unique within the array, and an integer representing a target difference. Determine the number of pairs of elements in the array that have a difference equal to the target difference.

For example, consider the array [1, 3, 5] and a target difference 2. There are two pairs: [1,3] and [3,5], that have the target difference.

**Function Description **

Complete the function kDifference in the editor below. The function must return an integer count of the number of pairs within a having a difference of k.

kDifference has the following parameter(s):

- a[a[0],…a[n-1]]: array of integers to test
- k: the target difference

**Sample Input 0**

1 2 3 4 5 6 7 8 |
5 1 5 3 4 2 2 |

**Sample Output 0**

1 2 |
3 |

**Explanation 0**

Count the number of pairs in a = [1, 5, 3, 4, 2] whose difference is k = 2. The following three pairs meet the criterion: (1, 3), (5, 3), and (4, 2).

**Solution**

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 42 |
public class kDifference { public static int kDifference(int[] a, int k) { int ans = 0; Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>(); for (int i= 0; i<a.length; i++) { int n = a[i]; if (!map.containsKey(n)) { map.put(n, new HashSet<>()); } map.get(n).add(i); } for (int i= 0; i<a.length; i++) { int n = a[i]; int diff = Math.abs(n - k); if (map.containsKey(diff)) { Set<Integer> indices = map.get(diff); ans += indices.size(); if (indices.contains(i)) { ans--; } } } return ans; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in5.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } int k = scanner.nextInt(); System.out.println(kDifference(a,k)); } } |