Solution: Implement Trie (Prefix Tree)
Understand how to build and use a Trie (prefix tree) for efficient string insertion, complete word search, and prefix matching. This lesson covers implementing core Trie functions with attention to time and space complexity, helping you apply this pattern in coding interviews.
We'll cover the following...
Statement
Trie is a tree-like data structure used to store strings. The tries are also called prefix trees because they provide very efficient prefix-matching operations. Implement a trie data structure with three functions that perform the following tasks:
Insert (word): This inserts a word into the trie.
Search (word): This searches the given word in the trie and returns TRUE if the complete word is found (i.e., all characters match and the last node is marked as the end of a word). Otherwise, return FALSE.
Search prefix (prefix): This searches the given prefix in the trie and returns TRUE if the prefix path exists in the trie (i.e., all prefix characters match), regardless of whether the last node is marked as the end of a word. Otherwise, return FALSE.
Constraints:
-
word.length,prefix.length