There are 2 approaches to solving this problem. If you're certain that both the arrays are small (let's say their length is less than 100), you can follow this approach:
let find = [1, 2, 3];
let nums = [1, 2, 3, 4, 5, 6];
let containsAll = true;
for (let i = 0; i < find.length; i++) {
if (!nums.includes(find[i])) {
containsAll = false;
break;
}
}
console.log(containsAll);
This approach simply checks whether each element in find array is there in nums array. If it encounters any number in find array which is not present in nums array, it will set the containsAll variable to false and break or come out of loop.
However this approach uses Javascript .includes method and thus runtime complexity is O(find.length * nums.length), since .includes uses linear search. Check this: Runtime complexity of JS .includes
To improve this we can run binary search on each element of find array. Code:
let find = [1, 6, 34];
let nums = [1, 4, 6, 8, 5, 16];
nums = nums.sort((a, b) => a - b); //sort for binary search
let containsAll = true;
for (let i = 0; i < find.length; i++) {
if (!binarySearch(nums, find[i])) {
console.log("Not found: ", find[i]);
containsAll = false;
return;
}
}
function binarySearch(arr, element) {
let start = 0,
end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (element == arr[mid]) {
return true;
} else if (element < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
console.log("containsAll: ", containsAll);
The resultant complexity is O(log(nums.length) * find.length).