KatInterview

Design an In-Memory Sentence Search Index

Data Structure DesignModel answer
HardModel answerData Structure DesignData Structure DesignInverted IndexString

Last updated

Design a data structure that supports adding, removing, and efficiently querying sentences by keyword in real time.

Create a data structure named SentenceIndexer that stores text sentences associated with numeric IDs and allows efficient term-based searching.

Your implementation must provide the following methods:

  1. add_sentence(sentence_id: int, text: str) -> None: Indexes a sentence under the given ID. Sentences should be split into lowercase alphanumeric tokens (ignoring spaces and non-alphanumeric characters).
  2. remove_sentence(sentence_id: int) -> None: Deletes the sentence corresponding to sentence_id from the index, cleaning up all references.
  3. search(query: str) -> List[int]: Returns a list of sentence IDs that contain the specified query word (case-insensitive), ordered by sentence_id in ascending order.

Constraints

  • text contains only spaces and alphanumeric characters.
  • sentence_id is a unique positive integer.
  • The search method must be significantly faster than scanning through every stored sentence.

Example

indexer = SentenceIndexer()
indexer.add_sentence(1, "Hello world")
indexer.add_sentence(2, "Hello there")
indexer.add_sentence(3, "World of coding")

indexer.search("hello")  # Returns [1, 2]
indexer.search("world")  # Returns [1, 3]

indexer.remove_sentence(1)
indexer.search("hello")  # Returns [2]

Edge Cases to Handle

  • Searching for a term that does not exist in any index sentence.
  • Deleting a sentence_id that is not currently indexed (should perform a no-op).
  • Sentences containing repeated words (the ID should only be returned once per query match).

Hints

Hint 1

A direct scan through all sentences per query is too slow. Consider how search engines map words to matching document IDs.

Hint 2

When a sentence is removed, how can you immediately know which word postings need to be updated without scanning the entire word index?

Hint 3

Think about maintaining two complementary mappings: one from terms to sentence IDs, and another from sentence IDs to terms.