Find Pair with given Sum in the Array

Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x.

Solution 1st: Using sorting + binary search (nlog(n))
https://ide.geeksforgeeks.org/d4GdbW8p8J

import java.io.*;
import java.util.*;
import java.util.Arrays;

class GFG {
    public static void main (String[] args) {
        int arraySize, sumUp;
        Scanner sc = new Scanner(System.in);
        arraySize = sc.nextInt();
   
        int array[] = new int[arraySize];
        for(int i=0;i<arraySize;i++)
            array[i] = sc.nextInt();
   
        sumUp = sc.nextInt();
        Arrays.sort(array);
   
        int startIndex, endIndex;
        startIndex=0;
        endIndex=arraySize-1;
   
        while(startIndex<endIndex){
            if(array[startIndex]+array[endIndex]==sumUp)
                System.out.println(array[startIndex++] +" + "+ array[endIndex--] +" = "+sumUp);
            else if(array[startIndex]+array[endIndex]<sumUp)
                startIndex++;
            else
                endIndex--;
        }
   
        if(array[startIndex]+array[endIndex]!=sumUp)
            System.out.println("No such pair present");
    }
}

Solution 2nd: Using Hashing (O(n))
https://ide.geeksforgeeks.org/sjViggyebs

import java.io.*;
import java.util.*;
import java.util.HashSet;

class GFG {
    public static void main (String[] args) {
        int arraySize, sumUp, remainingSum;
        Scanner sc = new Scanner(System.in);
        arraySize = sc.nextInt();
   
        int array[] = new int[arraySize];
        for(int i=0;i<arraySize;i++)
            array[i] = sc.nextInt();
   
        sumUp = sc.nextInt();
        HashSet<Integer> hash = new HashSet<Integer>();
        boolean flag=false;
   
        for(int i=0; i<arraySize; i++){
            remainingSum = sumUp - array[i];
            if(hash.contains(remainingSum)){
                System.out.println(array[i]+" + "+remainingSum+" = "+sumUp);
                flag=true;
            }
            hash.add(array[i]);
        }
   
        if(flag!=true)
            System.out.println("No such pair present");
    }
}

Also, see:

Comments

  1. Best explanation.
    Thanks,
    https://www.flowerbrackets.com/hashset-in-java/

    ReplyDelete

Post a Comment

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )