Search code examples
javaautocompletetrie

Implement basic autocomplete in Java


Given an array of words and phrases, given a key, return :

  • All words that start with the key
  • All phrases that contain a word that start with key

For example:

wordbank = ["bang", "base", "bore", "band", "This is a baffling problem];

key = "ba";

autocomplete(wordbank, key) should return ["bang", "base", "band", "This is a baffling problem]

I used a Trie to do it, but just wondering if this is a good solution?

To run, just enter java Test in the terminal. The test case in the link is not the same as the example here.


Solution

  • The code may be simplified in the following way. Add a set of autocomplete results to each node of the try. When inserting a word in a try, simultaneously add autocomplete set to each visited node. To perform an autocomplete, just return autocomplete set for the corresponding node.

    This solution adds one line to insertWord and getWordsWithPrefix, while completely remove the need of buildWords.