![]() |
VOOZH | about |
Given two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[] is a subset of a[]. Both arrays are not sorted, and elements are distinct.
Examples:
Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1]
Output: trueInput: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4]
Output: trueInput: a[] = [10, 5, 2, 23, 19], b = [19, 5, 3]
Output: false
Table of Content
The very basic approach is to use two nested loops, the outer loop picks each element from b[], and the inner loop searches for this element in a[] and check for all elements in b[].
true
Sort both arrays and use two pointers to traverse them. If the current element of a[] is smaller, move the pointer in a. If the elements match, move both pointers. If the current element of a[] is greater than b[], then b[j] is missing in a[], so return false.
true
We can use a hash set to store elements of a[], this will help us in constant time complexity searching. We first insert all elements of a[] into a hash set. Then, for each element in b[], we check if it exists in the hash set.
true