Search⌘ K

Array Subset

Discover how to create functions that determine if one array is a subset of another by examining each element's presence. Learn to handle duplicates and optimize for time and space complexity. Explore solutions using arrays, objects, and ES2015 Maps to manage different data types effectively.

Array Subset

Instructions

Write a function that accepts two parameters, both arrays. The arrays can have both strings and numbers. Return true if the second array is a subset of the first.

In other words, determine if every item in the 2nd array is also present somewhere in the 1st array.

Input: Array of Numbers & Strings, Array of Numbers & Strings

Output: Boolean

Examples

arraySubset([2, 1, 3], [1, 2, 3]); // -> true
arraySubset([2, 1, 1, 3], [1, 2, 3]); // -> true
arraySubset([1, 2], [1, 2, 3]); // -> false
arraySubset([1, 2, 3], [1, 2, 2, 3]); // -> false

Hints

  • This problem has multiple solutions with different time complexities.
  • We’ll need to consider how to deal with repeats, such as when an item is present twice.

Node.js
function arraySubset(arr, sub) {
// Your code here
}

Solution 1

Node.js
function arraySubset(arr, sub) {
if(sub.length > arr.length) {
return false;
}
for(let i = 0; i < sub.length; i++) {
const arrIndex = arr.indexOf(sub[i]);
if(arrIndex === -1) {
return false;
}
delete arr[arrIndex];
}
return true;
}
...