Problem Statement
In this problem, we will be given two arrays, and we need to find whether one array is a subset of another array. Note that, both the arrays are not sorted and both the arrays have distinct elements.
Sample Example
Input:
A1[]={22,1,13,19,64}
A2[]={1,64,22}
Output:
A2[] is a subset of A1[]
Explanation:
We see that all elements of A2 are present inside the array A1. Hence one array is a subset of another array
Brute Force Approach
The naive approach to this program is very simple.
- Check if each element of A2 is present inside A1.
- If it is the case, return true
- Otherwise return False.
Implementation in C++
// program to find whether an array is a subset of another array
#include <bits/stdc++.h>
using namespace std;
// function to check if A2 is a subset of A1
bool isA2SubsetOfA1(int arr1[], int arr2[], int n, int m){
int i, j; // pointers for iterating over arr1, arr2
for(i=0;i<m;++i){
// check if current element of A2 exists in A1 or not
for(j=0;j<n;++j){
if(arr1[j]==arr2[i])
break;
}
// current element doesn't exist in A1 hence it's not a subset
if(j==n) return false;
}
return true;
}
int main(){
// sizes of the array A1, A2
int n = 5;
int m = 3;
int arr1[n] = {11, 5, 3, 7, 1};
int arr2[m] = {11, 1, 7};
cout<<"A2 is"<<(isA2SubsetOfA1(arr1, arr2, n, m)?"":" not")<<" a subset of A1";
return 0;
}
Output:
A2 is a subset of A1
Complexity Analysis
Time complexity: O(m*n) since for each element it's checking inside entire array A1 if it exists or not
Space complexity: O(1) as no extra space is being used.