Search~35 min2s · 256 MBtarget O(total letters + n log n) time, O(total letters × k) spacetrie
A search box suggests completions while the user types. The app keeps a list of past searches, and each has a count of how many times it was searched.
For each typed prefix, the box shows the k best searches that start with it. Searches with a higher count come first. When two counts are equal, the alphabetically smaller search comes first.
Write suggest(words, counts, queries, k).
words[i] is a past search written in lower case letters, and counts[i] is how many times it was searched. All the words are different.queries, find the words that start with it. A word starts with itself.k.Input: words = ["car", "card", "care", "cart", "cat", "cab"], counts = [40, 90, 90, 10, 60, 10], queries = ["ca", "car", "cart", "d", "cab"], k = 3
Output: ["card,care,cat", "card,care,car", "cart", "", "cab"]The words ranked best first are: card (90), care (90), cat (60), car (40), cab (10), cart (10).
| Typed so far | Words with that start, best first | The best 3 |
|---|---|---|
| ca | card (90), care (90), cat (60), car (40), cab (10), cart (10) | card, care, cat |
| car | card (90), care (90), car (40), cart (10) | card, care, car |
| cart | cart (10) | cart |
| d | none | empty |
| cab | cab (10) | cab |
The words card and care both have a count of 90, so card comes first alphabetically. For ca, five words match, and the best three are card, care and cat. For d, no word matches.
Input: words = ["b", "a"], counts = [5, 5], queries = ["a", "b", "c"], k = 1
Output: ["a", "b", ""]Both words have a count of 5, but they start with different letters. Each query matches one word, and c matches none.
Input: words = ["pen", "pencil", "pens"], counts = [1, 1, 1], queries = ["pen"], k = 2
Output: ["pen,pencil"]All three counts are equal, so alphabetical order decides: pen, pencil, pens. The best two are pen and pencil.
1 ≤ words.length ≤ 50,000; counts has the same length; words are different1 ≤ counts[i] ≤ 1,000,000,0001 ≤ queries.length ≤ 50,000; 1 ≤ k ≤ 10Checking every word for every query costs up to 50,000 × 50,000 = 2.5 × 10^9 prefix checks. A trie lets a query follow its letters in at most 10 steps. Suppose every trie node already holds its best k words. Then each query takes about 10 steps, and building the trie costs one step per letter.