Pair Sum in Integer Array

Vignesh Kanna
2 min readOct 26, 2020
If you cannot see this meme image you have done sin in your last life !!!

Problem Statement:
Given an Array, find the existence of a “Target Sum” of two indices elements in the array of Integers
Example:
[3, 4, 9, 1, 2] and Target = 6
Ouput = true(4+2)

Algorithm:
1) Naive (NlogN):
a) Sort the given Array using custom or inBuilt Sorting Function
b) Use two pointer(one at left-most index, and second at right-most index)
c) Do below steps till left index is strictly lesser than right index…
d) If Sum of both indices element is equal to target return true
e) If Sum is smaller than target increment left index
f) Else decrement the right
2) Optimised (N):
a) Intialise a HashSet or Custom-Hashing array
b) For each element in the array do below steps…
c) Find the difference between target and array element
c1) If the difference present in HashSet… return true
c2) Else put the difference in HashSet

  Naive Solution//method to find the existence of pairSUm in array using sorting
public static boolean isSumExistUsingSort(int[] arr, int len, int target){
Arrays.sort(arr); //first sort the array to use TWO POINTER
int left = 0, right = len-1;
while(left< right){
int sum = arr[left] + arr[right];
if(sum == target) return true; //return true if pairSum obtained
if(sum< target){
left++; //if sum got is smaller than target move left pointer to 1 place right
}
else{
right--; //if sum got is bigger than target move right pointer to 1 place left
}
}
return false;
}
Optimised Solution//method to find the pair sum existence using hashSet
public static boolean isSumExistUsingHash(int[] arr, int length, int target){
HashSet<Integer> hs = new HashSet<>(); //Intialising the hashset object to be used
for(int ele: arr){
int difference = target- ele;
if(hs.contains(difference)) return true;
//return true if difference(pairSum) exist in set
else{
hs.add(ele);
}
}
return false; //return false if difference(pairSum) of all element in array not in set
}

--

--