Practice/Google/Leetcode 642. Design Search Autocomplete System
CodingMust
Build a real-time search suggestion engine that provides autocomplete functionality. The system processes user input character by character and returns the top 3 most relevant search suggestions based on historical search data.
Your system must:
When the user types '#', the current input sequence is saved as a new search (or increments the frequency if it already exists), and the system resets for the next query.
Implement a class with a constructor that takes two arrays: sentences (strings) and times (their corresponding frequencies)
Implement an input(c) method that:
c as inputc is not '#'c is '#'Results must be sorted by frequency (descending), then lexicographically (ascending) for ties
Only return sentences that match the accumulated prefix from previous inputs
c is a lowercase letter, space, or '#'inputExample 1:
Initialize: sentences = ["mobile phone", "mouse pad", "monitor"], times = [10, 5, 8] Input: 'm' → ["mobile phone", "monitor", "mouse pad"] Input: 'o' → ["mobile phone", "monitor", "mouse pad"] Input: 'u' → ["mouse pad"] Input: '#' → []
Explanation: After 'm', all three sentences match and are ranked by frequency. After 'mo', the same three still match. After 'mou', only "mouse pad" matches. The '#' saves "mou" as a new sentence with frequency 1.
Example 2:
Initialize: sentences = ["best buy", "best price", "best deal"], times = [3, 3, 3] Input: 'b' → ["best buy", "best deal", "best price"] Input: 'e' → ["best buy", "best deal", "best price"]
Explanation: All three sentences have the same frequency, so they're sorted alphabetically. Only the top 3 are returned.
Example 3:
Initialize: sentences = ["hello world"], times = [1] Input: 'h' → ["hello world"] Input: 'e' → ["hello world"] Input: 'l' → ["hello world"] Input: 'l' → ["hello world"] Input: 'o' → ["hello world"] Input: ' ' → ["hello world"] Input: 'w' → ["hello world"] Input: 'o' → ["hello world"] Input: 'r' → ["hello world"] Input: 'l' → ["hello world"] Input: 'd' → ["hello world"] Input: '#' → []
Explanation: The sentence matches at each step. After '#', the frequency of "hello world" becomes 2.