Learn-dsa..in 30 days!



























CC-14 : Find common elements in two arrays.

Description:

Given 2 String arrays arr1 and arr2 as input, find and return the common elements.

Test cases and expected outputs:

Input Parameters Expected outputs
strArray1 = {"hello", "good", "morning"};
strArray2 = {"good"};
Common Elements : good
strArray1 = {"great", "big", "boat"};
strArray2 = {"good", "great", "boat"};
Common Elements : great,boat
strArray1 = {"north", "south", "east"};
strArray2 = {"west"};
No common elements are present

Pseudocode:

The java method should accept following input parameters: arr1 (String array), arr2 (String array).
Initialize a variable set1 of type HashSet to hold the input elements.
Initialize and ArrayList variable named commonAl to store the common elements that we find in the two input arrays.
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 set1.
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:
If arr2[idx] in already present in set1:
If commonAl does not contain arr2[idx]:
Add arr2[idx] to commonAl.
At completion of above loop, commonAl contains all the common elements.
Use an iterator to access elements from commonAl and add the same to String array named commonArr. Return commonArr.

Code:

public String[] setArraysFindCommon(String[] arr1, String[] arr2) {
	HashSet<String> set1=new HashSet<String>();
	ArrayList<String> commonAl=new ArrayList<String>();
	for (int idx=0; idx < arr1.length; idx++) {
		set1.add(arr1[idx]);
	}
	for (int idx=0; idx < arr2.length; idx++) {
		if(set1.contains(arr2[idx])) {
			if(!commonAl.contains(arr2[idx])) {
				commonAl.add(arr2[idx]);
			}
		}
	}
	String[] commonArr= commonAl.toArray(new String[commonAl.size()]);
	return commonArr;
}

Click here to download and run code and test cases !