208. Implement Trie (Prefix Tree) πŸ”₯

Medium

Problem:

Implement the insert, search, and startWith methods of the Trie.

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // return True
trie.search("app");     // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app");     // return True

https://leetcode.com/problems/implement-trie-prefix-tree/arrow-up-right

Solution:

  • insert(): In a Trie, each character serves as a key for the child nodes, deepening progressively, and only becomes True when the word is fully formed.

  • search(): Continue deep traversal character by character and, in the end, check if the word is True.

  • startsWith(): Iterating over the string using a loop, keep descending through child nodes, only checking if the child node exists or not.

Last updated