I\'m trying to implement a data structure that supports autocomplete on a website. I\'ve managed to implement an iterative version of a Trie. It supports the two primary methods
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.end = "#"
def words_with_prefix(self, prefix: str):
'''
return all possible words with common prefix
'''
node = self.root
for c in prefix:
if c not in node:
return []
node = node[c]
ans = []
self._words_with_prefix_helper(node, prefix, ans)
return ans
def _words_with_prefix_helper(self, node, prefix, ans):
for k in node:
if k == self.end:
ans.append(prefix)
continue
self._words_with_prefix_helper(node[k], prefix + k, ans)
complete implementation