spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

642. Design Search Autocomplete System #383

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Resolves: #225

Algorithm:

Let's consider what we are doing with the input here. After we are given some char, we only return the top three of the new char if the new char appears in these top three after the previous character. This naturally corresponds to Trie like structure, where characters have children going down the tree.

What we should to is then create a Trie from the input sentences. This is pretty easy to implement. For the frequencies part, we first place them into a map. While creating the Trie, we also keep the top three words for each trie node too, inserting if frequencies are suitable. We keep this list sorted for convenient insertion, as it only has at most 3 elements.

For the input we receive, we simply go down the trie, returning the "topThree" list. When we receive the termination input wirh '#', we add the previous characters to the trie as we had done initially with the input sentences, perhaps updating the top three lists on the way.