Learn-dsa..in 30 days!



























CC-10 : Find pairs with required sum.

Description:

Given an integer input parameter reqSum, find all pairs in an input array of integers named arr that sum up to it.

Test cases and expected outputs:

Input Parameters Expected outputs
intArray1 = {1,2,3,4,9,-3,0};
Required Sum : 3
Found pair that sum up to requiredSum : [2,1]
Found pair that sum up to requiredSum : [0,3]
intArray8 = {1,3,-5,7,-9,11,13};
requiredSum=0;
No pairs that sum up to requiredSum were found !

Pseudocode:

The java method should accept following input parameters: arr (int array), reqSum (integer).
Initialize a variable named complementsHash of type HashSet to hold the input elements of arr.
Initialize integer variable named complement to 0.
Initialize integer variable named isComplementFound to false.
Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
Calculate reqSum=arr[idx] and set this value in variable complement. This means if complement is added to arr[idx] the sum will be equal to reqSum. This way we can find pairs of integers that sum up to reqSum.
If complementsHash contains complement:
arr[idx] and complement are a pair of integers in arr that sum up to reqSum. Print arr[idx] and complement to console.
Set variable isComplementFound to true.
Add arr[idx] to complementsHash.
At completion of above loop, if isComplementFound is true then one or more pairs of integers that sum up to reqSum have been found in arr. If isComplementFound is false no pairs of integers that sum up to reqSum were found in arr. Return isComplementFound.

Code:

public static void arrayFindPairsWithSum(int[] arr, int reqSum) throws Exception{
	HashSet<Integer> complementsHash=new HashSet<Integer>();
	int complement=0;
	boolean isComplementFound=false;
	for (int idx=0; idx < arr.length; idx++ ) {
		complement=reqSum-arr[idx];
		if (complementsHash.contains(complement)==true) {
			System.out.println("\n Found pair that sum up to requiredSum : ["+
					arr[idx]+","+complement+"]\n");
			isComplementFound=true;
		}
		complementsHash.add(arr[idx]);
	}
	if (isComplementFound==false) {
		System.out.println("\n No pair that sum up to requiredSum  were found !\n");		
	}
}

Click here to download and run code and test cases !