Pair With Sum

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

/*

Find a pair that sums up to the "8"


[1,2,3,9] sum = 8;
[1,2,4,4] sum = 8;

*/
//are they all integers? Yes
// whether they are all sorted list? Yes
// Do I need to provide the pair or just a yes/true or no/false? Just a boolean

// Approach#1: Iterate "elements" in nested loops, so for each try to add next
element to see if the sum is 8.
// if we total sum is 8, then return true. else keep looking for others.
import java.util.Set;
import java.util.HashSet;
public class PairWithSum{

public static void main(String[] args){


int[] elements = new int[]{1,2,3,9};
// int[] elements = new int[]{1,8,2,4,4};

boolean result = isPairWithSumExists2(elements, 8);


System.out.println("Is Pair Found? "+result);
}

private static boolean isPairWithSumExists(int[] elements, int sum){


for(int i=0; i< elements.length; i++){
for(int j=0; j< elements.length; j++){
if(i!=j){
int localSum = elements[i]+elements[j];
if(localSum == sum){
return true;
}
}
}
}
return false;
}
// Time Complexity: O(n2) and Space Complexity: O(1);

//Improve Complexity;
// Null Checks & Error Handling.

//Approach#2:
//nlog(n)
//1+x = 8 => x=8-1

private static boolean isPairWithSumExists2(int[] elements, int sum){


Set<Integer> complimentSet = new HashSet(); // Stores the compliments
of each element to check if that exists in this set
for(int i=0; i< elements.length; i++){
//Calculate the compliment and check that agains the set.
int compliment = sum - elements[i];
if(complimentSet.contains(compliment)){
return true;
}else{
complimentSet.add(compliment);
}
}
return false;
}
//Pass1: {} => {7}
//Pass2: {7} => {7,6,4}
}

You might also like