Count of lists which are not a subset of any other given lists

• Last Updated : 02 Sep, 2021

Given N lists of strings, the task is to find the count of lists which are not a sublist of any other given lists.
Examples:

Input: [[“hey”, “hi”, “hello”], [“hey”, “bye”], [“hey”, “hi”]]
Output:
Explanation
The third list is a subset of the first list, hence the first and the second list are the required lists.
Input: [[“geeksforgeeks”, “geeks”], [“geeks”, “geeksforgeeks”]]
Output:
Explanation: Both the lists comprise of same set of strings.

Approach
Follow the steps below to solve the problem:

1. First of all, enumerate all the possible strings in all vectors, i.e. assign them an integer.
2. Then, use a Bitset for all individual lists to store the strings present in them.
3. Compare the bitsets. If one of the bitsets is a subset of another, ignore that list. Otherwise insert the index of that list in a set.
4. Print all the indices in the set.

Below code is the implementation of the above approach:

C++

 // C++ program to find all lists// which are not a subset of any// other given lists#include using namespace std; #define N 50005 // Function to print all lists which// are not a subset of any other listsvoid findNonSubsets(vector >& v,                    vector& ans){    unordered_map mp;    int id = 1;    // Enumerate all strings    // present in all lists    for (int i = 0; i < v.size(); i++) {        for (int j = 0; j < v[i].size(); j++) {            if (mp.count(v[i][j]) > 0)                continue;             mp[v[i][j]] = id++;        }    }     // Compute and store bitsets    // of all strings in lists    vector > v1;     for (int i = 0; i < v.size(); i++) {        bitset b;        for (int j = 0; j < v[i].size(); j++) {            b[mp[v[i][j]]] = 1;        }        v1.push_back(b);    }    for (int i = 0; i < v.size(); i++) {        bool flag = false;        for (int j = 0; !flag and j < v.size(); j++) {            if (i != j) {                // If one of the bitsets is                // a subset of another, the                // logical AND is equal to the                // subset(intersection operation)                if ((v1[i] & v1[j]) == v1[i]) {                    flag = true;                }            }        }         if (!flag) {            ans.push_back(i);        }    }    return;} // Driver Programsigned main(){    vector > v        = { { "hey", "hello", "hi" },            { "hey", "bye" },            { "hey", "hi" } };     vector ans;    findNonSubsets(v, ans);     if (ans.size() == 0) {        cout << -1 << endl;        return 0;    }     for (int i = 0; i < ans.size(); i++) {        cout << ans[i] << " ";    }     return 0;}
Output:
0 1

Time Complexity: O ( N * M )
Auxiliary Space: O ( N * M )

My Personal Notes arrow_drop_up