Learn-dsa..in 30 days!



























CC-7 :Check if arrays are equal/ contain the same elements.

Description:

Given two input arrays, check if the contents are same.

Test cases and expected outputs:

Input Parameters Expected outputs
strArray1 = {"hi", "hello", "hola"};
strArray2 = {"hello", "hola", "hi"};
The arrays are equal !
strArray1 = {"north", "south", "east"};
strArray2 = {"north", "west", "south"};
The arrays are *not* equal !

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 of arr1.
Check that arr1 and arr2 length ae the same, if not return false as then the arrays cannot be equal.
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 that is not common.
At completion of above loop, if we have not returned after finding a non=common element, it means the arr1 and arr2 are equal. Return true.

Code:

public boolean setArraysCheckEquality(String[] arr1, String[] arr2) {
	HashSet<String> set1=new HashSet<String>();
	if (arr1.length != arr2.length) {
		return false;
	}
	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 !