Pair with a given sum in an array using HashSet in Java

In this Java tutorial, we are going to find the existence of a pair in an array whose sum is equal to a given value using HashSet.

What is HashSet in Java?

Set is an unordered collection in which duplicates value cannot be stored. Set can be implemented by HashSet, LinkedHashSet, TreeSet.

The data structure for HashSet is a hash table. HashSet implements Set so it does not allows duplicate value. Objects inserted in HashSet need not be in the same order, they are inserted on basis of their hash code. The main feature of HashSet is fast searching.

Syntax : Set<data_type>variable_name = new HashSet<data_type>();

To learn,

What is HashSet.contains() in Java?

HashSet.contains() method in Java is used to search for a particular element in HashSet. It is used to check whether a specific element is present in HashSet or not.

                 Syntax : HashSet.contains(Specified_element);

The method returns true if specified element is present in HashSet otherwise false.

Algorithm:-

  1. The input value of ‘n’ and ‘sum’. Take an array a[] of n elements.
  2. Declare a HashSet ‘s’ of integers. And add all elements of array in HashSet using s.add() function.
  3.  Now check in the HashSet whether it contains sum-array[i] value using HashSet.contains() function and that value should be different from a[i].
  4. Finding (sum-a[i]) in HashSet, help us to find the second element of the pair in the array.

Java code to check for pairs with a given sum in Java using HashSet

import java.util.Scanner;
import java.util.*;
class Codespeedy
{
   public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    
      int n,sum,i;
      n=scan.nextInt();
      sum=scan.nextInt();
      
       Set<Integer>s = new HashSet<Integer>();
      
          int a[] = new int[1000];
      int flag=0;
      
      for(i=0;i<n;i++)
       {
           int x=scan.nextInt();
             a[i]=x;
            s.add(a[i]);
       }
        
    

        for(i=0;i<n;i++)
        {
            int check=sum-a[i];
            
              if(s.contains(check))
                    flag=1;
                  
                  if(check==a[i])
                     flag=0;
       }
       
      if(flag==1)
      System.out.println("yes");
      
      else
      System.out.println("no");
   }
}

INPUT

4 12
6 5 4 1

OUTPUT

no

In the example taken the value of the sum is 12. So, there is no pair existing in an array whose sum is 12. hence, the output is “no”.

You may also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *