How do you implement a Trie, and what are its applications?

Instruction: Describe the structure of a Trie and discuss its common use cases.

Context: This question is designed to assess the candidate's understanding of Tries and their application in tasks such as autocomplete and spell checking.

Updated

Official answer

A trie represents shared prefixes as paths. Each node maps a character to a child and records whether a complete stored word ends there. A prefix path alone does not establish word membership.

class Trie:
    def __init__(self):
        self.children = {}
        self.is_word = False

    def insert(self, word):
        node = self
        for char in word:
            if char not in node.children:
                node.children[char] = Trie()
            node = node.children[char]
        node.is_word = True

    def contains(self, word):
        node = self
        for char in word:
            node = node.children.get(char)
            if node is None:
                return False
        return node.is_word

After inserting cat, contains('cat') is true and contains('ca') is false. Inserting the empty string marks the root. This implementation is case-sensitive and does not normalize Unicode or perform fuzzy matching.

With expected constant-time dictionary child access, insertion and membership take O(m) for a length-m word. A prefix search finds its node in O(m), but enumerating completions also costs time proportional to visited/output content. Dense child arrays trade space for direct access; sparse maps and compressed paths offer different tradeoffs.

Applications include prefix completion and dictionary lookup. Ranking suggestions and finding misspellings require additional logic.

Source

Princeton Algorithms: tries.

Related Questions