Design Search Autocomplete System
Master this topic with zero to advance depth.
Design Search Autocomplete System
Design a search autocomplete system for a search engine. Users may input a sentence (at least one character and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that have a prefix the same as the part of the sentence already typed.
Visual Representation
Typed: "i"
Prefix "i" matches "i love you" (5), "island" (3), "ironman" (2).
Return: ["i love you", "island", "ironman"]
Typed: " " (space)
Prefix "i " matches "i love you" (5), "i a cool" (2).
Return: ["i love you", "i a cool"]Examples
Level I: HashMap (Brute Force Prefix Search)
Intuition
Maintain a HashMap of historical sentences and their counts. For every input, iterate through the entire map, collect sentences starting with the prefix, and sort them to find the top 3. Simple but O(N * L) per query.
Level III: Trie + Top-3 Cache
Intuition
Store each historical sentence in a Trie. Each node stores a list of the top 3 hot sentences passing through it. Update these lists incrementally to ensure O(1) query time (just return the list at the current node).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.