Learn-dsa..in 30 days!



























CC-9 : Check if an array is contained in another array.

Description:

Given two integer arrays arr1 and arr2, check if all elements of arr2 are contained in arr1.

Test cases and expected outputs:

Input Parameters Expected outputs
intArray1 = {1,33,54,56,22,98, 49, 99, 23, 27, 74};
intArray2 = {22, 23, 27};
Array1 contains all Array2 elements!
intArray5 = {45, 56, 86, 66, 34, 85, 36, 67, 49, 98, 56};
intArray6 = {56, 34, 89};
Array1 does *not* contain all Array2 elements !

Pseudocode:

The java method should accept following input parameters: arr1 (int array), arr2 (int array).
Initialize a variable set1 of type HashSet to hold the input elements of arr1.
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 *not* present, return false from the program as we have found an element of arr2 that is not present in arr1.
At completion of above loop, if we have not returned after finding a non-common element, it all elements of arr2 are contained in arr1. Return true.

Code:

public boolean setArraysContains(int[] arr1, int[] arr2) {
	HashSet<Integer> set1=new HashSet<Integer>();
	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 !