To check Array is a subset of another array or not

Write a program to check an array is a subset of another array or not.

Example:

Input:  mainArray={1,2,3,2,5,6,2}, subArray={2,2,2}
Output: true

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool isSubset(vector<int&mainArrayvector<int&subArray)
{

    int i = 0j = 0;
    int m = mainArray.size();
    int n = subArray.size();

    //sort both the arrays
    sort(mainArray.begin(), mainArray.end());
    sort(subArray.begin(), subArray.end());

    //apply two poniter approach
    while (i < n && j < m)
    {
        if (mainArray[j] == subArray[i])
        {
            i++;
            j++;
        }
        else if (mainArray[j] < subArray[i])
            j++;

        else if (mainArray[j] > subArray[i])
            return false;
    }

    if (i < n)
        return false;
    else
        return true;
}

int main()
{
    vector<intmainArray = {1232562};
    vector<intsubArray = {222};

    if (isSubset(mainArraysubArray))
    {
        cout << "true";
    }
    else
        cout << "false";

    return 0;
}


No comments:

Post a Comment