VOOZH about

URL: https://www.geeksforgeeks.org/dsa/auto-complete-feature-using-trie/

⇱ Auto-complete feature using Trie - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Auto-complete feature using Trie

Last Updated : 20 Feb, 2023

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.  

  1. Search for the given query using the standard Trie search algorithm.
  2. If the query prefix itself is not present, return -1 to indicate the same.
  3. If the query is present and is the end of a word in Trie, print query. This can quickly be checked by seeing if the last matching node has isEndWord flag set. We use this flag in Trie to mark the end of word nodes for purpose of searching.
  4. If the last matching node of the query has no children, return.
  5. Else recursively print all nodes under a subtree of last matching node.

Below are few implementations of the above steps. 


Output
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.
 

Comment
Article Tags: