Learn-dsa..in 30 days!



























CC-12 : Make pairs of same integers.

Description:

Given array of integers arr, check and return true if the integers can be grouped into pairs of 2 integers, where both integers in a pair are the same.

Test cases and expected outputs:

Input Parameters Expected outputs
intArray = {4,3,3,1,4,1}; Pairs can be made as required.
intArray = {4,4,4,4}; Pairs can be made as required
intArray = {9,9,9,1,2,2,2}; Pairs *cannot* be made as required

Pseudocode:

The java method should accept following input parameters: arr(integer array).
If (arr.length%2 !=0), return false as pairs cannot be made using all integers if number of integers is odd.
Initialize a variable hMap of type HashMap to hold integers from input arrays as keys, and the frequency of the integers as the values.
Iterate through arr using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
If hMap does not contain key arr[idx], then put key-value pair arr[idx] and 1 to hMap.
If hMap contains key arr(idx) with value freq, then put key-value pair arr(idx) and freq+1 to hMap.
After above loop completes, iterate through keys of hMap and check that the values (the integers frequencies) corresponding to keys are divisible by 2. If all integer frequencies are divisible by 2, then pairs can be formed successfully from the input array, so return true, else return false.

Code:

public boolean hashMapMakePairs(int[] arr) throws Exception{
	if (arr.length%2 !=0) {return false;}
	HashMap< Integer,Integer> hMap=new HashMap< Integer, Integer>();
	for (int idx=0; idx < arr.length; idx++) {
		if (hMap.containsKey(arr[idx])){
			int freq=hMap.get(arr[idx]);
			hMap.put(arr[idx], ++freq);
		}else {
			hMap.put(arr[idx], 1);
		}			
	}
	Iterator itr=hMap.keySet().iterator();
	int cntInt=0;
	while (itr.hasNext()) {
		cntInt=hMap.get(itr.next());
		if (cntInt % 2!=0) {
			return false;
		}
	}
	return true;		
}

Click here to download and run code and test cases !