Design Search Autocomplete System Problem
Description
LeetCode Problem 642.
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#').
You are given a string array sentences and an integer array times both of length n where sentences[i] is a previously typed sentence and times[i] is the corresponding number of times the sentence was typed. For each input character except '#', return the top 3 historical hot sentences that have the same prefix as the part of the sentence already typed.
Here are the specific rules:
- The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
- The returned top
3hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same hot degree, use ASCII-code order (smaller one appears first). - If less than
3hot sentences exist, return as many as you can. - When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
Implement the AutocompleteSystem class:
AutocompleteSystem(String[] sentences, int[] times)Initializes the object with thesentencesandtimesarrays.List<String> input(char c)This indicates that the user typed the characterc.- Returns an empty array
[]ifc == '#'and stores the inputted sentence in the system. - Returns the top
3historical hot sentences that have the same prefix as the part of the sentence already typed. If there are fewer than3matches, return them all.
- Returns an empty array
Example 1:
Input
["AutocompleteSystem", "input", "input", "input", "input"]
[[["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]], ["i"], [" "], ["a"], ["#"]]
Output
[null, ["i love you", "island", "i love leetcode"], ["i love you", "i love leetcode"], [], []]
Explanation
AutocompleteSystem obj = new AutocompleteSystem(["i love you", "island", "iroman", "i love leetcode"], [5, 3, 2, 2]);
obj.input("i"); // return ["i love you", "island", "i love leetcode"]. There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.
obj.input(" "); // return ["i love you", "i love leetcode"]. There are only two sentences that have prefix "i ".
obj.input("a"); // return []. There are no sentences that have prefix "i a".
obj.input("#"); // return []. The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.
Constraints:
n == sentences.lengthn == times.length1 <= n <= 1001 <= sentences[i].length <= 1001 <= times[i] <= 50cis a lowercase English letter, a hash'#', or space' '.- Each tested sentence will be a sequence of characters
cthat end with the character'#'. - Each tested sentence will have a length in the range
[1, 200]. - The words in each input sentence are separated by single spaces.
- At most
5000calls will be made toinput.
Solution
Approach: Trie + Collect the Subtree
All suggestions for a keystroke share the prefix typed so far, which is exactly what a trie groups together. Store every sentence in a trie, one character per edge (letters and space). The node where a sentence ends keeps its hot degree, the number of times it was typed, and the sentence itself.
We also keep the current search: the characters typed since the last '#', and node, the trie node for that prefix.
- A normal character
c: append it to the typed text and movenodeto its child forc. If there is no such child, no stored sentence has this prefix. Setnodeto "none", and keep it that way until the next'#', because a longer prefix cannot match either. Otherwise, collect every sentence in the subtree belownode, sort them by hot degree (higher first), with ties in ASCII order, and return the first three. '#': the user finished a sentence. Add it to the trie with one more use (it may already exist, then its count goes up), reset the typed text and setnodeback to the root. Return[].
Two details are easy to get wrong. First, the tie-break is plain ASCII order, so a space comes before every letter: "i love leetcode" beats "ironman". Second, the sentence finished with '#' must count from then on, even if it was never seen before, like "i a" in the example, and the next character starts a brand new search.
Moving node one step per character, rather than walking down from the root each time, saves re-reading the prefix.
Complexity: A keystroke costs O(1) to move node, plus O(S + m log m) to collect and sort, where S is the size of the subtree and m the number of sentences in it. '#' costs O(L) to insert a sentence of length L. The trie takes space proportional to the total length of all stored sentences.
class TrieNode:
def __init__(self):
self.children = {}
self.hot = 0 # how many times the sentence ending here was typed
self.sentence = ""
class AutocompleteSystem:
def __init__(self, sentences: List[str], times: List[int]):
self.root = TrieNode()
for s, t in zip(sentences, times):
self._add(s, t)
self.typed = []
self.node = self.root # trie node of the typed prefix (None: no sentence has it)
def _add(self, sentence, times):
node = self.root
for c in sentence:
node = node.children.setdefault(c, TrieNode())
node.hot += times
node.sentence = sentence
def input(self, c: str) -> List[str]:
if c == "#":
self._add("".join(self.typed), 1)
self.typed, self.node = [], self.root
return []
self.typed.append(c)
if self.node is not None:
self.node = self.node.children.get(c)
if self.node is None:
return []
# Collect every sentence below the prefix node, then keep the 3 best.
found, stack = [], [self.node]
while stack:
node = stack.pop()
if node.hot:
found.append((-node.hot, node.sentence))
stack.extend(node.children.values())
found.sort()
return [s for _, s in found[:3]]