Learn-dsa..in 30 days!



























CC-4 : Merge 2 arrays and remove duplicates.

Description:

Given two input arrays of the same data type, merge the 2 arrays and remove the duplicates from the merged array.

Test cases and expected outputs:

Input Parameters Expected outputs
intArray1 = {1,2,3,4};
intArray2 = {5,2,7,4};
1,2,3,4,5,7
intArray3 = {7,8};
intArray4 = {7,8};
7,8

Pseudocode:

The java method should accept following input parameters: arr1 (int array), arr2 (int array).
Initialize a variable merged of type LinkedHashSet to hold the input elements.
Using a for loop iterate through arr1, using idx as a loop variable with initial value 0 and increment idx till it reaches arr1.length-1:
Add arr1[idx] to merged.
Using a for loop iterate through arr2, using idx as a loop variable with initial value 0 and increment idx till it reaches arr2.length-1:
Add arr2[idx] to merged.
At completion of above loop, merged contains all the unique elements from arr1 and arr2 with duplicates removed.
Use an iterator to access elements from merged and add the same to integer array named retVal. Return retVal.

Code:

public int[] setMergeArrays(int[] arr1, int[] arr2) {
	HashSet<Integer> merged=new HashSet<Integer>();
	for (int idx=0; idx <arr1.length; idx++) {
		merged.add(arr1[idx]);
	}
	for (int idx=0; idx <arr2.length; idx++) {
		merged.add(arr2[idx]);
	}
	int[] retVal=new int[merged.size()];
	int idx=0;
	Iterator<Integer> itr=merged.iterator();
	while (itr.hasNext()) {
		retVal[idx]=itr.next().intValue();
		idx++;
	}
	return retVal;
}

Click here to download and run code and test cases !