Develop a trie.
Question Explain
This question is asking you to explain and implement a specific kind of data structure known as a trie, which is also referred to as prefix tree. It is a type of search tree, often used for searching through strings. The unique aspect of a trie compared to other binary search trees is that position of a node in the tree determines the key associated with that node.
Tries are typically used to store words for later retrieval, and enable you to search, insert, and delete strings effectively.
Points to remember while answering:
- Describe what a trie is and when it could be used.
- Explain how searching, insertion, and deletion operations work.
- Implement a trie (preferably in a common language, such as Java or Python).
Answer Example 1
A trie is an ordered tree data structure that is used to efficiently store and retrieve keys in a dataset of strings. It enables quick search, insert and delete operations. Leaves in a trie usually represent complete words, while every edge of a trie represents a character.
Here's a simple implementation of a Trie in Python:
class TrieNode:
def __init__(self):
self.children = {}
self.endOfString = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in word:
node = current.children.get(char)
if not node:
node = TrieNode()
current.children[char] = node
current = node
current.endOfString = True
def search(self, word):
current = self.root
for char in word:
node = current.children.get(char)
if not node:
return False
current = node
return current.endOfString
In this python implementation, we first define two classes: TrieNode
and Trie
. The TrieNode
class initialized with a dictionary "children" to store its children nodes and a boolean "endOfString" to denote the end of a word. The Trie
class contains methods to insert and search for words in the Trie.
Answer Example 2
Here's another implementation of a Trie, this time using Java:
class TrieNode {
private TrieNode[] links;
private final int R = 26;
private boolean isEnd;
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch) {
return links[ch - 'a'] != null;
}
public TrieNode get(char ch) {
return links[ch - 'a'];
}
public void put(char ch, TrieNode node) {
links[ch - 'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return isEnd;
}
}
This Java implementation begins by defining the TrieNode
class, which contains an array of "links" that represent connecting nodes, a constant integer 'R' that stands for the number of lowercase English letters. Additionally, it has a boolean 'isEnd' that denotes the end of word and methods to interact with these properties.
The "links" array in this implementation acts as the children of every node.
With a clear understanding of the structure of a trie and its operations, it should be easy to build upon this and implement a complete Trie.