Design an In-Memory Sentence Search Index
Data Structure DesignModel answerLast 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:
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).remove_sentence(sentence_id: int) -> None: Deletes the sentence corresponding tosentence_idfrom the index, cleaning up all references.search(query: str) -> List[int]: Returns a list of sentence IDs that contain the specified query word (case-insensitive), ordered bysentence_idin ascending order.
Constraints
textcontains only spaces and alphanumeric characters.sentence_idis a unique positive integer.- The
searchmethod 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_idthat 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Strategy
To achieve fast lookup times without scanning through every registered sentence, we utilize an Inverted Index—a mapping from each unique word token to the set of sentence IDs containing that token.
However, deletion poses a challenge if we only maintain an inverted index. If we attempt to delete sentence_id = 10, we would have to inspect every key in our inverted index to check if ID 10 is present. To optimize deletion to $O(W)$ time (where $W$ is the number of distinct words in the sentence being removed), we simultaneously maintain a Forward Index mapping each sentence_id to its set of unique word tokens.
Data Structures Used:
_inverted_index:dict[str, set[int]]— Maps normalized words to sets of matchingsentence_ids._forward_index:dict[int, set[str]]— Maps eachsentence_idto the set of normalized words present in that sentence.
Using set for posting lists automatically handles duplicated words within a single sentence, ensuring that a sentence ID appears at most once for any word token.
Algorithm Details
-
Tokenization: Convert input text to lowercase and extract contiguous sequences of alphanumeric characters using regex (
[a-z0-9]+). Using identical tokenization rules for both indexing and searching guarantees consistency. -
add_sentence(sentence_id, text):- If
sentence_idalready exists, first invokeremove_sentence(sentence_id)to prevent stale records. - Tokenize
textinto a unique set of words. - Store the set of words in
_forward_index[sentence_id]. - For each word, add
sentence_idto_inverted_index[word].
- If
-
remove_sentence(sentence_id):- Remove and retrieve the set of words associated with
sentence_idfrom_forward_index. If missing, simply return. - For each word in the set, remove
sentence_idfrom_inverted_index[word]. - If the set of IDs for a word becomes empty, delete the word key from
_inverted_indexto prevent memory leaks over time.
- Remove and retrieve the set of words associated with
-
search(query):- Tokenize
query. If the query yields anything other than exactly one token, return an empty list[]. - Retrieve the set of IDs associated with the query token from
_inverted_index. - Convert the set to a sorted list and return.
- Tokenize
Code Implementation
import re
from typing import Dict, List, Set
_WORD_PATTERN = re.compile(r"[a-z0-9]+")
def _tokenize(text: str) -> List[str]:
"""Converts input text to lowercase and splits into alphanumeric words."""
return _WORD_PATTERN.findall(text.lower())
class SentenceIndexer:
def __init__(self) -> None:
# Inverted index: word -> set of sentence_ids
self._inverted_index: Dict[str, Set[int]] = {}
# Forward index: sentence_id -> set of words
self._forward_index: Dict[int, Set[str]] = {}
def add_sentence(self, sentence_id: int, text: str) -> None:
# Replace existing entry if sentence_id is re-added
if sentence_id in self._forward_index:
self.remove_sentence(sentence_id)
words = set(_tokenize(text))
self._forward_index[sentence_id] = words
for word in words:
if word not in self._inverted_index:
self._inverted_index[word] = set()
self._inverted_index[word].add(sentence_id)
def remove_sentence(self, sentence_id: int) -> None:
words = self._forward_index.pop(sentence_id, None)
if words is None:
return # No-op if sentence_id doesn't exist
for word in words:
if word in self._inverted_index:
self._inverted_index[word].discard(sentence_id)
if not self._inverted_index[word]:
del self._inverted_index[word]
def search(self, query: str) -> List[int]:
tokens = _tokenize(query)
if len(tokens) != 1:
return []
target_word = tokens[0]
if target_word not in self._inverted_index:
return []
return sorted(self._inverted_index[target_word])
Complexity Analysis
-
Time Complexity:
add_sentence: $O(L + W)$ where $L$ is the string length and $W$ is the count of distinct words in the sentence. Tokenization takes $O(L)$, and inserting into sets takes $O(1)$ average time per word.remove_sentence: $O(W)$ where $W$ is the count of distinct words in the sentence being removed.search: $O(1)$ average dictionary lookup + $O(K \log K)$ sorting step, where $K$ is the number of matching sentence IDs.
-
Space Complexity:
- $O(N \cdot W_{avg})$ where $N$ is the number of sentences and $W_{avg}$ is the average number of unique words per sentence. The data is duplicated across the inverted and forward indices.