↓Skip to main content
  1. LeetCode/

LeetCode 208: Implement Trie (Prefix Tree)

·2 mins· ·
LeetCode Medium Hash-Table String Design Trie
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Wrong Answer → Accepted

Approach
#

Each trie node holds children (character → child) and is_end (whether a word ends here) (Trie). insert walks down, creating missing nodes, and sets is_end. search must also check is_end at the last node, while startsWith succeeds whenever the walk completes. Each operation is O(L), independent of how many words are stored.

My Attempts
#

What I wrote was not a trie at all: a list of every word, search via in and startsWith calling startswith on each word, O(N · L) per call.

  • Attempt 1’s startsWith returned False as soon as the first word failed, never checking the rest: after inserting a and aba, startsWith("ab") returned False.
  • search’s else branch wrote False without return, yielding None on a miss.

Solution
#

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word: str) -> None:
        node = self.root
        for c in word:
            node = node.setdefault(c, {})
        node["#"] = True

    def _walk(self, s):
        node = self.root
        for c in s:
            if c not in node:
                return None
            node = node[c]
        return node

    def search(self, word: str) -> bool:
        node = self._walk(word)
        return node is not None and "#" in node

    def startsWith(self, prefix: str) -> bool:
        return self._walk(prefix) is not None

Complexity
#

Each operation is O(L); space is the total length of all words.

Mistakes to Avoid
#

  • search must check the end marker; app is a prefix of apple but not necessarily a word.
  • Using "#" as the end marker is safe only because words contain lowercase letters alone.

Interview Explanation
#

Each trie node is a dict of children plus an end marker. Insert walks down creating nodes and marks the end; search walks and checks the marker; startsWith succeeds if the walk completes. Each operation is O(L).

Related

LeetCode 981: Time Based Key-Value Store
·2 mins
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 note: store a (timestamp, value) list per key, with timestamps increasing; get binary searches the last timestamp <= the query
LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)
LeetCode 138: Copy List with Random Pointer
·2 mins
LeetCode Medium Hash-Table Linked-List
LeetCode 138 note: the first pass maps old nodes to new ones, the second wires next and random; seed the dictionary with None -> None