Learn-dsa..in 30 days!



























CC-5 : Check if 2 arrays are disjoint.

Description:

Given 2 input arrays, check if they have no common elements.

Test cases and expected outputs:

Input Parameters Expected outputs
strArray1 = {"hi", "hello", "hola"};
strArray2 = {"good", "better", "best"};
The arrays are disjoint!
strArray3 = {"great", "big", "ship"};
strArray4 = {"small", "fast", "boat"};
The arrays are disjoint!
strArray5 = {"north", "south", "east"};
strArray6 = {"west", "north", "east"};
The arrays are *not* disjoint !

Pseudocode:

The java method should accept following input parameters: arr1 (int array), arr2 (int array).
Initialize a variable set1 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 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:
Check if arr2[idx] in already present in set1. If it is present, return false from the program as we have found a common element.
At completion of above loop, if we have not returned after finding a common element, it means the arr1 and arr2 are disjoint. Return true.

Code:

public boolean setArraysCheckDisjoint(String[] arr1, String[] arr2) {
	HashSet<String> set1=new HashSet<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])) {
			return false;
		}
	}
	return true;
}

Click here to download and run code and test cases !