Check whether an array is a subset of another array

Easy

Problem

Given arrays a1 and a2, return true if every element of a2 is present in a1. The values within each array are distinct.

Example 1

Input:  a1 = [11, 1, 13, 21, 3, 7], a2 = [11, 3, 7, 1]
Output: true

Example 2

Input:  a1 = [10, 5, 2, 23, 19], a2 = [19, 5, 3]
Output: false

3 is missing from a1.

Also asked as: Find whether an array is a subset of another array

Test cases

Case 1

Input:    [11,1,13,21,3,7], [11,3,7,1]
Expected: true

Case 2

Input:    [10,5,2,23,19], [19,5,3]
Expected: false

Case 3

Input:    [1,2,3], []
Expected: true

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Hash set

Time O(n + m)Space O(n)

Put the bigger array in a set; every element of the smaller must be present.

function isSubset(big, small) {
const set = new Set(big);
return small.every((x) => set.has(x));
}