MongoDB Interview Question

What is inverted search? Implement Inverted search with following functionalities: insert(String doc) search(String term) delete(String doc) andSerach(String term1, String term2)

Interview Answer

Anonymous

Apr 30, 2025

This was my solution public class InvertedIndex { // Map from term -> set of documents containing that term private Map> map; public InvertedIndex() { map = new HashMap<>(); } // Insert a document into the index public void insert(String doc) { String[] words = doc.toLowerCase().split("\\W+"); for (String word : words) { map.computeIfAbsent(word, k -> new HashSet<>()).add(doc); } } // Search for documents containing a single term public List search(String term) { Set result = map.getOrDefault(term.toLowerCase(), Collections.emptySet()); return new ArrayList<>(result); } // Delete a document from the index public void delete(String doc) { for (Set docs : map.values()) { docs.remove(doc); if (docs.isEmpty()) { map.remove(word); } } } // Search for documents containing BOTH term1 and term2 public List andSearch(String term1, String term2) { Set set1 = map.getOrDefault(term1.toLowerCase(), Collections.emptySet()); Set set2 = map.getOrDefault(term2.toLowerCase(), Collections.emptySet()); Set result = new HashSet<>(set1); result.retainAll(set2); // intersection return new ArrayList<>(result); } } I am not sure why they did not like this solution. My tests had passed in the interview and I did not recieve feedback from the recruiter