isSubset of two arrays in JavaScript


Our goal in the above problem statement is to use Javascript functionalities and determine whether or not the given arrays are subsets of each other. So using loops we can fix this problem.

Understanding the problem

The problem description specifies that we have to identify that the given array is a subset of another array. Or we have to check that all of the items in the second array are present in the first array. For example, suppose we have an array like ['a', 'b', 'c', 'd', 'e'] and a second array ['b', 'd', 'e']. So when we compare these two arrays to check the subset the result will be true. Because all of the items of the second array are present in the first array.

Logic for the given problem

For solving the problem we will create a set from the first array with the usage of Set constructor and enable the has method to check for item presence. Next we will traverse over the second array and verify that every item exists in the set or not. If the item is not found we will return false. If we have successfully traversed over all the items in the second array then we will conclude that it is a subset of the first array and return true.

Algorithm

Step 1: Use a function to check that the given array is a subset of another array or not. Then inside the function we will pass two arrays as input.

Step 2: Next create a set out of the input array.

Step 3: Traverse the array items of the array with the help of a loop.

Step 4: Verify the condition if the current item from the first array is present in the second array or not. If the condition is satisfied then return true otherwise false.

Example

// Function to check for subset of arrays
function isArraySubset(arr1, arr2) {
   const set = new Set(arr1);

   for (let i = 0; i < arr2.length; i++) {
      if (!set.has(arr2[i])) {
         return false;
      }
   }

   return true;
}

const arr1 = [10, 24, 38, 14, 85];
const arr2 = [24, 14, 85];
const arr3 = [16, 67, 78];

console.log(isArraySubset(arr1, arr2));
console.log(isArraySubset(arr3, arr1));

Output

true
false

Complexity

The time complexity of this algorithm is O(n), here n is the size of the second array. As we have used the ‘has’ method which has an average time complexity of O(1). So we have performed n lookups in the set that is why the complexity is resulting in a linear time.

Conclusion

The given code in our program effectively determines that one array is a subset of the second array with the help of Set. The code has a time complexity of O(n) which is an efficient solution for most practical scenarios.

Updated on: 14-Aug-2023

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements