Here is the full interview question "Coding - Serialize and Deserialize Dictionary Trie" asked at xAI:
Problem Statement: Implement a dictionary trie that allows for insertion and search operations. Additionally, implement methods to serialize and deserialize the trie, allowing it to be stored in a string format.
Examples:
Insertion:
A / \ T I / \ \ E N N \ S / \ T E \ DSearch:
Starts with:
Constraints:
Hints:
Solution: `python class TrieNode: def init(self): self.children = {} self.is_end_of_word = False
class Trie: def init(self): self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
def starts_with(self, prefix: str) -> bool:
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def serialize(self) -> str:
def serialize_helper(node, depth=0):
if not node:
return "#" * (depth + 1)
res = ""
for char, child in node.children.items():
res += char + serialize_helper(child, depth + 1)
if not res:
res = "#" * (depth + 1)
return res
return serialize_helper(self.root)
def deserialize(self, data: str) -> None:
def deserialize_helper(node, chars):
if not chars:
return
char = chars[0]
if char != "#":
node.children[char] = TrieNode()
deserialize_helper(node.children[char], chars[1:])
else:
node.is_end_of_word = True
deserialize_helper(node, chars[1:])
self.root = TrieNode()
deserialize_helper(self.root, list(data))
trie = Trie() words = ["a", "to", "tea", "ted", "ten", "i", "in", "inn"] for word in words: trie.insert(word)
print(trie.search("a")) # True print(trie.search("b")) # False
prefix = "te" result = [word for word in words if word.startswith(prefix)] print(trie.starts_with(prefix)) # True print(result) # ["tea", "ted", "ten"]
serialized_trie = trie.serialize() print(serialized_trie)
new_trie = Trie() new_trie.deserialize(serialized_trie) print(new_trie.search("a")) # True `
Source: