Implement Trie
Try to solve the Implement Trie (Prefix Tree) problem.
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 found. Otherwise, return FALSE.
- Search prefix (prefix): This searches the given prefix in the trie and returns TRUE, if found. Otherwise, return FALSE.
Constraints:
-
word.length
,prefix.length
- The strings consist only of lowercase English letters.
- At most, calls in total will be made to the functions.
Examples
The Insert function does not return anything. The Search and Search prefix functions return TRUE if the input is found in the trie. Otherwise, they will return FALSE.
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Implement Trie
Given a trie with the words [bat, bag, make, broom, bait]
, what will be the output of the following query?
search('bait')
TRUE
FALSE
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: The game below is only for the Insert function.
Try it yourself
Implement your solution in Trie.java
in the following coding playground. You will need the provided supporting code to implement your solution.
import java.util. * ;class Trie {public Trie() {// Write your code here}// inserting string in triepublic void insert(String word) {// Write your code here}// searching for a stringpublic boolean search(String word) {// Replace this placeholder return statement with your codereturn false;}// searching for a prefixpublic boolean searchPrefix(String prefix) {// Replace this placeholder return statement with your codereturn false;}}