Java Program to Find Two Elements whose Sum is Equal to a Given Number

This is the Java Program to Find Two Elements whose Sum is Equal to a Given Number.

Problem Description

Given an array of n integers and a value, say m. Find out the pairs of elements from the array, whose sum values m.
Example:
Array = [ 1, 2, 4, 5, 8, 10, 11] m = 13

Output :
{8, 5}
{11, 2}

Problem Solution

Iterate through the array and in a temporary variable, say x, store the difference of the current array element and the value m. Search for value x, in the map, if x is present in the map, then the pair of elements x and the current array element, sums to m, else store x in the map.

Program/Source Code

Here is the source code of the Java Program to Find Two Elements whose Sum is Equal to a Given Number. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to Find Two Elements whose Sum is Equal to a Given Number.
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6. import java.util.HashMap;
  7.  
  8. public class PairsHavingGivenSum {
  9.     // Function to print the pair of elements having a given sum
  10.     static void printPairs(int[] array,int sum)
  11.     {
  12.         HashMap<Integer,Integer> obj=new HashMap<>();
  13.         int i,search;
  14.         System.out.println("The pairs having sum "+sum+" are");
  15.         for(i=0;i<array.length;i++){
  16.             search=sum-array[i];
  17.             if(obj.containsValue(search)){
  18.                 System.out.println(array[i]+" and "+search);
  19.             }
  20.             else
  21.             {
  22.                 obj.put(i,array[i]);
  23.             }
  24.         }
  25.     }
  26.     // Main function to read the input
  27.     public static void main(String[] args) {
  28.         BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
  29.         int size;
  30.         System.out.println("Enter the size of the array");
  31.         try{
  32.             size=Integer.parseInt(br.readLine());
  33.         }
  34.         catch(Exception e)
  35.         {
  36.             System.out.println("Invalid Input");
  37.             return;
  38.         }
  39.         int[] array=new int[size];
  40.         System.out.println("Enter array elements");
  41.         int i;
  42.         for(i=0;i<array.length;i++){
  43.             try{
  44.                 array[i]=Integer.parseInt(br.readLine());
  45.             }
  46.             catch(Exception e)
  47.             {
  48.                 System.out.println("Invalid element. Enter it again");
  49.                 i--;
  50.             }
  51.         }
  52.         int sum;
  53.         System.out.println("Enter the sum you want to look for");
  54.         try{
  55.             sum=Integer.parseInt(br.readLine());
  56.         }
  57.         catch(Exception e)
  58.         {
  59.             System.out.println("Invalid Input");
  60.             return;
  61.         }
  62.         printPairs(array,sum);
  63.     }
  64. }
Program Explanation

1. In function printPairs(), firstly a hashmap is created HashMap obj=new HashMap<>().
2. The loop for(i=0; i<array.length; i++), sets the value search to sum – array[i] in each iteration.
3. The condition if(obj.containsValue(search)) looks for the variable search in the hashmap.
4. If it is present, then the present element and the element search has the given sum in the array.
5. Otherwise, the value search is added to the hashmap.

advertisement
advertisement

Time Complexity: O(n) where n is the number of elements in the array.

Runtime Test Cases
 
Case 1 (Simple Test Case) :
 
Enter the size of the array
7
Enter array elements
1
2
4
5
8
10
11
Enter the sum you want to look for
13
The pairs having sum 13 are
8 and 5
11 and 2
 
Case 2 (Simple Test Case - another example):
 
Enter the size of the array
10
Enter array elements
12
324
45
34
123
435
23
56
32
47
Enter the sum you want to look for
79
The pairs having sum 79 are
34 and 45
56 and 23
47 and 32

Sanfoundry Global Education & Learning Series – Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.