![]() |
VOOZH | about |
We are given a Trie with a set of strings stored in it. Now the user types in a prefix of his search query, we need to give him all recommendations to auto-complete his query based on the strings stored in the Trie. We assume that the Trie stores past searches by the users.
For example if the Trie store {"abc", "abcd", "aa", "abbbaba"} and the User types in "ab" then he must be shown {"abc", "abcd", "abbbaba"}.
Prerequisite Trie Search and Insert.
Given a query prefix, we search for all words having this query.
Below are few implementations of the above steps.
hel hell hello help helping helps
Time Complexity: O(N*L) where N is the number of words in the trie and L is the length of the longest word in the trie.
Auxiliary Space: O(N*L+N * ALPHABET_SIZE)
How can we improve this?
The number of matches might just be too large so we have to be selective while displaying them. We can restrict ourselves to display only the relevant results. By relevant, we can consider the past search history and show only the most searched matching strings as relevant results.
Store another value for the each node where isleaf=True which contains the number of hits for that query search. For example if "hat" is searched 10 times, then we store this 10 at the last node for "hat". Now when we want to show the recommendations, we display the top k matches with the highest hits. Try to implement this on your own.