208. Implement Trie (Prefix Tree)

var Trie = function() {
    this.dict = {};
};

/** 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {
    let currentDict = this.dict;
    for (let i = 0; i < word.length; i++) {
        const c = word[i];
        currentDict[c] = currentDict[c] ?? {};
        currentDict = currentDict[c];
    }

    currentDict.done = true;
};

/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
    let currentDict = this.dict;
    for (const c of word) {
        if (currentDict[c] === undefined) return false;
        currentDict = currentDict[c];
    }
    
    return !!currentDict.done
};

/** 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {
    let currentDict = this.dict;
    for (const c of prefix) {
        if (currentDict[c] === undefined) return false;
        currentDict = currentDict[c];
    }

    return true;
};

/** 
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

Last updated