You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.

[Problem Link]

  • Add all elements to a Set
  • To figure if an element arr[i] and some X make a pair, we check if
    (arr[i] – Target) is in Set

    why?
    arr[i] – X = Target
    X = arr[i] – Target

    // Complete the pairs function below.
    static int pairs(int k, int[] arr) {
        Set<Integer> arrSet = new HashSet<Integer>();
        for ( int i = 0 ; i < arr.length ; i++ )
            arrSet.add(arr[i]);
 
        int ret = 0;
        for ( int i = 0 ; i < arr.length ; i++ )
            if (arrSet.contains(arr[i]-k))
                ret++;
        return ret;
    }