What is Trie and How to implement it?

By Prajwal Haniya

Tech-letter #15 | March 28, 2023

Trie

Building an application using trie

Let’s try to build a simple autocomplete application using trie. This involves all the methods that I have explained above. The only differencethat you notice will be in thesearch method`.


    class Trie {

        // constructor
        // ...

        // All methods same as above
        // ...

        searchWord(word) {
            let currentNode = this.root;
            for (let i = 0; i < word.length; i++) {
                let char = word[i];
    
                if (!currentNode.children[char]) {
                    return [];
                }
                currentNode = currentNode.children[char];
            }
    
            return this.getAllWords(currentNode, word);
        }

        getAllWords(node, prefix) {
            const words = [];
            if (node.isEndOfWord) {
                words.push(prefix)
            }

            for (let child in node.children) {
                words.push(...this.getAllWords(node.children[child], prefix + child));
            }
            return words;
        }
    }

The search method takes a partial word as an argument and returns an array of all possible word completions that start with the given word.

Understanding getAllWords() method

let us take an example

   root
   |-- 'a'
   |   |-- 'p'
   |   |    |-- 'p'
   |   |         |-- 'l'
   |   |              |-- 'e'
   |   |                   |-- '*'
   |   |-- 'r'
   |        |-- 'm'
   |             |-- '*'
   |-- 'c'
   |    |-- 'a'
   |         |-- 'r'
   |              |-- '*'
   |-- 't'
        |-- 'e'
             |-- 'a'
                  |-- 'm'
                       |-- '*'