#208

Implement Trie (Prefix Tree)

Medium
Hash TableStringDesignTrieTriePrefix Tree
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a trie structure, where each node represents a character of a word. This allows for efficient insertion and search operations, reducing the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a TrieNode class that contains a dictionary for children and a boolean to mark the end of a word.
  2. 2Step 2: In the Trie class, initialize a root node.
  3. 3Step 3: For 'insert', traverse the trie character by character, creating new nodes as needed, and mark the end of the word.
  4. 4Step 4: For 'search', traverse the trie and check if the entire word exists.
  5. 5Step 5: For 'startsWith', traverse the trie to check if any word starts with the given prefix.
solution.py28 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end_of_word = False
5class Trie:
6    def __init__(self):
7        self.root = TrieNode()
8    def insert(self, word):
9        node = self.root
10        for char in word:
11            if char not in node.children:
12                node.children[char] = TrieNode()
13            node = node.children[char]
14        node.is_end_of_word = True
15    def search(self, word):
16        node = self.root
17        for char in word:
18            if char not in node.children:
19                return False
20            node = node.children[char]
21        return node.is_end_of_word
22    def startsWith(self, prefix):
23        node = self.root
24        for char in prefix:
25            if char not in node.children:
26                return False
27            node = node.children[char]
28        return True

Complexity note: The time complexity is O(n) for insert, search, and startsWith, where n is the length of the word or prefix. This is because we only traverse the length of the word/prefix. Space complexity is O(n) as we store nodes for each character in the trie.

  • 1Tries are efficient for prefix-based searches.
  • 2Each node represents a character, allowing for quick traversal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.