Find a pair with the given difference

Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n.

Examples:

Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
Output: Pair Found: (2, 80)

Input: arr[] = {90, 70, 20, 80, 50}, n = 45
Output: No Such Pair
class GFG {
    public static int findPair(int[] arr, int diff) {
        HashMap<Integer, Boolean> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], true);
            if (map.containsKey(arr[i] + diff) || map.containsKey(arr[i] - diff)) 
                return 1;
        }
        return -1;
    }
}

Last updated