Search Suggestions System (Trie, dictionary-scale word count)
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-02-28
Problem Statement
Design a Search Suggestions System (autocomplete) that provides real-time suggestions to users as they type. The system should be able to handle a large dictionary of words/phrases and rank suggestions based on frequency of use or popularity.
Functional Requirements
1.Add Word / Update Frequency
•Insert new words into the dictionary.
•Maintain a frequency count for each word to track popularity.
•Update frequency whenever a word is searched or selected.
2.Get Suggestions by Prefix
•Given a prefix, return the top-K suggestions.
•Suggestions should be ranked by frequency, and alphabetically if frequencies tie.
•Suggestions should update dynamically as the user types each character.
3.Optional Features
•Delete a word or reduce its frequency.
•Support multi-word phrases.
Non-Functional Requirements
•Scalability: Support millions of words efficiently.
•Low Latency: Return suggestions in real-time (<100 ms).
•Memory Efficiency: Use space-optimized Trie structure.
•Extensibility: Easy to add new words or languages.
Edge Cases & Constraints
•Prefix not found → return empty list.
•Duplicate word insertions → increment frequency.
•Multiple words with same frequency → sort alphabetically.
•Frequent updates → Trie nodes must efficiently maintain top-K suggestions.
Design Hints
•Data Structures:
•TrieNode → contains children map, optional isWord flag, frequency, and top-K suggestions.
•Min-Heap / Sorted List → maintain top-K words at each node for fast retrieval.
•Classes / Interfaces:
•SearchSuggestionSystem → main API to insert words and get suggestions.
•Trie → manages Trie nodes and insertion logic.
•TrieNode → node in Trie with children and frequency info.
•WordFrequencyStore → keeps global counts of all words.
•Design Patterns:
•Strategy Pattern → optionally support different ranking strategies (frequency-based, recency-based).
•Observer Pattern → updating frequencies can propagate changes to maintain top-K lists.
Example Flow
1.Insert words: "apple" (10), "app" (20), "application" (5), "apt" (3)
2.User types "ap" → return [app, apple, application]
3.User types "app" → return [app, apple, application]
4.User selects "apple" → frequency updated → top-K lists updated accordingly
Evaluation Areas
•Efficient Trie + top-K maintenance.
•Clean class design & OOP principles.
•Handling edge cases (duplicates, empty prefix, ties).
•Scalability and real-time performance considerations.