Find a pair that match to the given value x from the input array.
Input : [1,5,10,3,4] X=15
Output: [5,10]
Code:
package wordpress; import java.util.*; public class FindX { public static HashSet<List<Integer>> findXFromGivenArray(Integer[] input, int x) { HashSet<List<Integer>> result = new HashSet<>(); HashSet<Integer> hashSet = new HashSet<>(); for (Integer value : input) { hashSet.add(value); } for (Integer value : input) { List<Integer> pair = new LinkedList<>(); if (hashSet.contains(x - value)) { pair.add(value); pair.add(x - value); result.add(pair); hashSet.remove(value); } } return result; } public static void main(String[] args) { System.out.println(findXFromGivenArray(new Integer[]{1, 5, 10, 3, 4}, 15)); // [5,10] System.out.println(findXFromGivenArray(new Integer[]{1, 2, 3, 4}, 4)); // [1,3] [2,2] System.out.println(findXFromGivenArray(new Integer[]{1,2}, 10)); // [] System.out.println(findXFromGivenArray(new Integer[]{-1,-3,-8,-5}, -4)); // [-1,-3] } }