Given two List sentence and List queries
I have two find the occurrence of queries in sentences.
Example,
- "Pulkit likes StackOverflow and coding" 
- "Pulkit does not like Reddit" 
- "Pulkit like ice cream" 
Queries
- Pulkit coding 
- like 
- does 
The function should return for the queries
- sentence[0] 
- sentence[1], sentence[2] 
- sentence[1] 
I solved this question already using HashMap but it is quadratic and I am wondering how to do it in linear time.
Solution
     public static void findMatch(List<String> sentences, List<String> queries) {
        // Write your code here
        // Split the sentences into terms and map them by index
        Map<Integer, Set<String>> sentencesSplit = new HashMap<>();
        for (int j = 0; j < sentences.size(); j++) {
            String[] splitSentence = sentences.get(j).split(" ");
            Set<String> sentenceSet = new HashSet<>();
            sentencesSplit.put(j, sentenceSet);
            for (int i = 0; i < splitSentence.length; i++) {
                sentenceSet.add(splitSentence[i]);
            }
        }
        // Split the query into terms and map them by index
        Map<Integer, String[]> queriesSplit = new HashMap<>();
        for (int i = 0; i < queries.size(); i++) {
            queriesSplit.put(i, queries.get(i).split(" "));
        }
        for (int i = 0; i < queries.size(); i++) {
            String found = null;
            for (int j = 0; j < sentences.size(); j++) {
                String[] splitQuery = queriesSplit.get(i);
                Set<String> sentenceStringList = sentencesSplit.get(j);
                boolean notFound = false;
                for (int k = 0; k < splitQuery.length; k++) {
                    if (!sentenceStringList.contains(splitQuery[k])) {
                        notFound = true;
                        break;
                    }
                }
                if (!notFound) {
                    if (found == null) {
                        found = "" + j;
                    } else {
                        found += " " + j;
                    }
                }
            }
            if (found == null) {
                found = "-1";
            }
            System.out.println(found);
        }
    }
 
    