// Java implementation using Hashing import java.io.*; import java.util.HashSet; class PairSum { static void printpairs(int arr[], int sum) { HashSet<Integer> s = new HashSet<Integer>(); for (int i = 0; i < arr.length; ++i) { int temp = sum - arr[i]; // checking for condition if (s.contains(temp)) { System.out.println("Pair with given sum " + sum + " is (" + arr[i] + ", " + temp + ")"); } s.add(arr[i]); } } // Main to test the above function public static void main(String[] args) { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; printpairs(A, n); } } // OUTPUT : Pair with given sum 16 is (10, 6)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter