Data Structures19 sections · 729 units
Open in Course

Trie Implementation

Complete solution

class TrieNode:
    constructor():
        this.children = {}
        this.isEnd = false

class Trie:
    constructor():
        this.root = TrieNode()

    function insert(word):
        node = this.root
        for c in word:
            if c not in node.children:
                node.children[c] = TrieNode()
            node = node.children[c]
        node.isEnd = true

    function search(word):
        node = this._findNode(word)
        return node != null and node.isEnd

    function startsWith(prefix):
        return this._findNode(prefix) != null

    function _findNode(s):
        node = this.root
        for c in s:
            if c not in node.children:
                return null
            node = node.children[c]
        return node

The helper _findNode avoids duplicating traversal logic between search and startsWith.