InterviewDB
Experience
Inverted Index: Build a Full-Text Search Index Over a Document Collection
phone
Interview Experience
Round 1 Coding
Problem
Build an inverted index over a collection of documents. Support adding documents, querying for documents containing a single word, and AND queries returning documents that contain all given words.
python
class InvertedIndex:
def add_document(self, doc_id: int, text: str) -> None:
...
def search(self, word: str) -> set[int]:
**returns** set of doc_ids containing word (case-insensitive)
...
def search_all(self, words: list[str]) -> set[int]:
# AND query: doc must contain every word
...
def search_any(self, words: list[str]) -> set[int]:
# OR query: doc must contain at least one word
...
Example
idx = InvertedIndex()
idx.add_document(1, "the quick brown fox")
idx.add_document(2, "the fox jumped over")
idx.add_document(3, "a quick brown dog")
idx.search("fox") -> {1, 2}
idx.search_all(["quick","brown"]) -> {1, 3}
idx.search_any(["fox","dog"]) -> {1, 2, 3}
Follow-ups
- How do you handle common stop words like "the" or "a"? Should they be indexed?
- How would you extend the index to store word positions so you can support phrase queries like
"quick brown"? - How do you rank results by relevance (e.g., TF-IDF) instead of returning an unordered set?
- How would you handle document updates — what must be re-indexed when a document's text changes?
Full Details
Round 1 Coding
Problem
Build an inverted index over a collection of documents. Support adding documents, querying for documents containing a single word, and AND queries returning documents that contain all given words.
python
class InvertedIndex:
def add_document(self, doc_id: int, text: str) -> None:
...
def search(self, word: str) -> set[int]:
**returns** set of doc_ids containing word (case-insensitive)
...
def search_all(self, words: list[str]) -> set[int]:
# AND query: doc must contain every word
...
def search_any(self, words: list[str]) -> set[int]:
# OR query: doc must contain at least one word
...
Example
idx = InvertedIndex()
idx.add_document(1, "the quick brown fox")
idx.add_document(2, "the fox jumped over")
idx.add_document(3, "a quick brown dog")
idx.search("fox") -> {1, 2}
idx.search_all(["quick","brown"]) -> {1, 3}
idx.search_any(["fox","dog"]) -> {1, 2, 3}
Follow-ups
- How do you handle common stop words like "the" or "a"? Should they be indexed?
- How would you extend the index to store word positions so you can support phrase queries like
"quick brown"? - How do you rank results by relevance (e.g., TF-IDF) instead of returning an unordered set?
- How would you handle document updates — what must be re-indexed when a document's text changes?
Free preview. Unlock all MongoDB questions →
About This Question
This is a candidate experience report from a mongodb interview during the phone round.