class Solution {
  public:
    vector<int> solve(int N, vector<string> &S, int Q, vector<string> &Query) {
        // code here
        vector<int> dp(1<<21,N+5),ans;
        for(int i=0;i<N;i++){
            vector<int> freq(26,0);
            for(auto it:S[i]){
                freq[it-'a']=1;
            }
            int num=0;
            for(int j=0;j<20;j++){
                num+=(freq[j]*(1<<j));
            }
            dp[num]=min(dp[num],i);
        }
        for(int i=(1<<21)-1;i>=0;i--){
            for(int j=0;j<20;j++){
                if(i&(1<<j)){
                    int y=i^(1<<j); dp[y]=min(dp[y],dp[i]);
                }
            }
            if(dp[i]>N){
                dp[i]=-1;
            }
        }
        for(auto it:Query){
            int num=0;
            for(auto i:it){
                int d=i-'a'; num|=(1<<d);
            }
            ans.push_back(dp[num]);
        }
        return ans;
    }
};